我試圖附加到一個從空開始的文本文件,每次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貢獻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);
添加回答
舉報
0/150
提交
取消