亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

追加到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 關注
  • 190 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號