为了账号安全,请及时绑定邮箱和手机立即绑定

追加到android中的文本文件

追加到android中的文本文件

30秒到达战场 2024-01-28 16:29:14
我试图附加到一个从空开始的文本文件,每次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文件夹中
查看完整描述

2 回答

?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

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



查看完整回答
反对 回复 2024-01-28
?
动漫人物

TA贡献1815条经验 获得超10个赞

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");

然后打开一个 FileOutputStream

FileOutputStream fos = new FileOutputStream(file);


查看完整回答
反对 回复 2024-01-28
  • 2 回答
  • 0 关注
  • 37 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信