FileReaders readLine返回始终为null JAVA

时间:2018-05-01 12:47:28

标签: java file filereader

在java中编写程序我试图读取被视为存储的文件的内容。我有一个函数来修改商店中对象的数量,每个产品组成一行,第一个单词是prodCode,第二个是它的数量。 这是功能:

public static void modifyAmount(String prodCode, String newAmount){
    try{
        File magazzino = new File("Magazzino.txt");
        BufferedReader fromFile = new BufferedReader(new FileReader("Magazzino.txt"));
        FileWriter toFile = new FileWriter(magazzino);
        String oldContent="";
        String line;
        String lineToReplace = prodCode + " " + amountRequest(prodCode);
        String newLine = prodCode + " " + newAmount;

        while((line = fromFile.readLine()) != null){
            oldContent = oldContent + line + "\n";
            System.out.println("leggendo " + line);
        }
        System.out.println(oldContent);
        String newContent = oldContent.replaceAll(lineToReplace, newLine);
        toFile.write(newContent);

        toFile.close();
        fromFile.close();
    }catch(IOException e){
        e.printStackTrace();
    }
}

它的结果是它不会进入while循环,因为第一个readLine结果为null,尽管文件格式正确,但是' amountRequest'功能正常,输入正确。

Magazzino.txt:

1 12
3 25
4 12

3 个答案:

答案 0 :(得分:3)

您可能遇到了麻烦,因为您尝试使用不同的文件句柄同时读取和写入文件。我建议首先读取文件,然后关闭FileReader,然后创建一个FileWriter来写入它。

答案 1 :(得分:1)

问题是在您阅读文件内容之前,您正在创建一个FileWriter实例,它将清除该文件。

FileWriter toFile = new FileWriter("Magazzino.txt");将清除文件

解决方案是在读完文件后创建FileWriter实例。

public static void modifyAmount(String prodCode, String newAmount){
    try{
        File magazzino = new File("Magazzino.txt");
        BufferedReader fromFile = new BufferedReader(new FileReader("Magazzino.txt"));
        String oldContent="";
        String line;
        String lineToReplace = prodCode + " " + amountRequest(prodCode);
        String newLine = prodCode + " " + newAmount;

        while((line = fromFile.readLine()) != null){
            oldContent = oldContent + line + "\n";
            System.out.println("leggendo " + line);
        }
        fromFile.close();

        System.out.println(oldContent);
        String newContent = oldContent.replaceAll(lineToReplace, newLine);

        FileWriter toFile = new FileWriter(magazzino);
        toFile.write(newContent);

        toFile.close();
    }catch(IOException e){
        e.printStackTrace();
    }
}

答案 2 :(得分:-1)

您打开文件两次,同时进行读写。 一旦你这样做,

FileWriter toFile = new FileWriter(magazzino);

您的文件已被删除。自己检查一下。
实际上,使用此行,您将创建一个新的空文件,用于编写而不是旧文件。

我建议读取文件,然后关闭,然后写入。

您还可以尝试使用附加的笔文件:new FileWriter("filename.txt", true); 这不会删除旧文件,允许您阅读它。但是,新数据将附加到最后。

如果您想将文件用作状态或存储空间,我建议您查看 sqlite https://www.sqlite.org/index.html