有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

文件文件读取器读取行返回总是空的JAVA

用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”函数工作正常,输入正确

马加兹诺。txt:

1 12
3 25
4 12

共 (3) 个答案

  1. # 1 楼答案

    打开一个文件两次,同时进行读写操作。 你一说完这句话

    FileWriter toFile = new FileWriter(magazzino);
    

    你的文件被删除了。你自己检查一下
    实际上,通过这一行,您正在创建一个新的空文件来写入,而不是原来的文件

    我建议先读文件,然后关闭,再写

    您还可以尝试为附加new FileWriter("filename.txt", true); 这不会删除旧文件,允许您读取它。不过,新的数据将被追加到最后

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

  2. # 2 楼答案

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

  3. # 3 楼答案

    问题是,在读取文件内容之前,您正在创建一个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();
        }
    }