![](/img/trans.png)
[英]BufferedReader returns null, even though there is text in the file
[英]BufferedReader readline reading null even though there is text in the file
基本上,我正在嘗試創建一個簡單的數據庫應用程序,並在每個學生條目中自動生成 ID。 程序讀取前一個最高 ID 並將其加 1 以創建下一個。 但是,即使文本文檔中有數字,BufferedReader 在使用 readLine 時也會不斷返回 null
我檢查了我的 int 解析是否是問題,但我意識到它是 bufferedreader,方法是將 readline 保存到一個變量然后打印它,在那里我得到了 null 的結果。 我還嘗試使用不起作用的掃描儀文件讀取,並檢查了所有相關的類和方法以試圖弄清楚。
此代碼創建 topsid 文件並寫入 0 以對其進行初始化,該文件被讀取為 null
if(MiscProcesses.firstStartup() == false) //method that checks if these files exist
{
File topsid = new File("topsid.txt");
FileWriter fw = new FileWriter(topsid);
fw.write("0");
fw.close();
}
此代碼負責讀取文件並因此找到更高的 id 值
Student (String[] studata)
{
//checking highest SID
File topsid = new File("topsid.txt");
FileWriter fw = new FileWriter(topsid);
FileReader fr = new FileReader(topsid);
BufferedReader br = new BufferedReader(fr);
//checking high sid file and getting new sid
String test = br.readLine();
System.out.println(test+" <test"); <this ends up printing null
int sid;
sid = Integer.parseInt(test)+1;
System.out.println(sid);
fw.write(Integer.toString(sid));
this.id = sid;
...
br.close();
fr.close();
fw.close();
}
當我在第二個代碼運行之前打開 topsid 文件時,一切都很好,文件包含一個零。 我希望緩沖讀取器讀取“0”,但它只是讀取 null,當我在代碼運行后打開文件時,里面的數據被刪除。
FileWriter fw = new FileWriter(topsid);
FileReader fr = new FileReader(topsid);
BufferedReader br = new BufferedReader(fr);
像這樣創建FileWriter
將在您讀取現有文件的內容之前對其進行踩踏。
如果您想從文件中讀取某些內容,然后再寫回某些內容,請在讀取文件后創建FileWriter
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.