BufferedReader readline 读取 null,即使文件中有文本

BufferedReader readline reading null even though there is text in the file

基本上,我正在尝试创建一个简单的数据库应用程序,在每个学生条目中自动生成 ID。该程序读取先前的最高 ID 并将其加 1 以创建下一个。 但是,即使文本文档中包含数字,BufferedReader 在使用 readLine

时仍会返回 null

我检查了我的 int 解析是否有问题,但我通过将 readline 保存到一个变量然后打印它来意识到这是 bufferedreader,我得到的结果为 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 文件时,一切正常,文件包含一个零。 我希望 bufferedreader 读取“0”,但它只是读取 null,当我在代码运行后打开文件时,里面的数据被删除。

        FileWriter fw = new FileWriter(topsid);
        FileReader fr = new FileReader(topsid);
        BufferedReader br = new BufferedReader(fr);

像这样创建 FileWriter 会在您读取其内容之前破坏现有文件。

如果你想从文件中读取一些东西,然后写回一些东西,在你从它读取后FileWriter 创建。