追加到android中的文本文件

我试图附加到一个从空开始的文本文件,每次addStudent()调用该方法时,它都会student.toString()向该文件添加一行。我似乎没有遇到任何异常,但由于某种原因,在方法调用之后,文件仍然为空。这是我的代码。


public void addStudent() {

        Student student = new Student();

        EditText fName = findViewById(R.id.first_name);

        EditText lName = findViewById(R.id.last_name);

        EditText studentGpa = findViewById(R.id.gpa);

        String firstName = String.valueOf(fName.getText());

        String lastName = String.valueOf(lName.getText());

        String gpa = String.valueOf(studentGpa.getText());


        if(firstName.matches("") || lastName.matches("") || gpa.matches("")) {

            Toast.makeText(this, "Please make sure none of the fields are empty", Toast.LENGTH_SHORT).show();

        } else {

            double gpaValue = Double.parseDouble(gpa);

            student.setFirstName(firstName);

            student.setLastName(lastName);

            student.setGpa(gpaValue);

            try {

                FileOutputStream fos = openFileOutput("students.txt",  MODE_APPEND);

                OutputStreamWriter osw = new OutputStreamWriter(fos);

                osw.write(student.toString());

                osw.flush();

                osw.close();

            } catch(FileNotFoundException e) {

                e.printStackTrace();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

这里可能有什么问题?文件students.txt本身位于assets文件夹中


30秒到达战场
浏览 42回答 2
2回答

陪伴而非守候

问题可能在于手机上不存在“资产”目录。所以如果我理解正确的话你可能检查了错误的文件。

动漫人物

What might be the problem here? The file students.txt itself is located in assets folder.如果它位于资产文件夹中,那么您应该使用 AssetsManager 打开它的输入流。资产文件夹中的文件是只读的,因此尝试写入它们是没有意义的。FileOutputStream fos = openFileOutput("students.txt",  MODE_APPEND);这将在您的应用程序的私有内存中创建一个文件。代码看起来没问题。但尝试使用文件管理器或其他应用程序在手机上查找该文件是没有意义的,正如所说的那样,该文件只是您应用程序的私有内部存储器。您使用“studends.txt”的相对路径,现在您不知道该文件所在的位置。那么该文件位于 指示的路径中getFilesDir()。您也可以使用完整路径 File file = new File(getFilesDir(), "students.txt");然后打开一个 FileOutputStreamFileOutputStream fos = new FileOutputStream(file);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java