Files.readAllLine() 在 FileWriting 后不工作

Files.readAllLine() not working after FileWriting

希望你一切顺利,这是我的第一个问题
我遇到了麻烦:
我的目标是从代码片段(字段、属性、构造函数)创建 java 文件 我试图通过在读取和写入文件之间进行更改来做到这一点。
读取文件获取旧值,删除结束“}”
写入文件 : 新的一段代码,加上结束“}”
我尝试的问题是 Files.readAllLine() 或 FileWriter() 不工作。 您可以在下面找到我的源代码。

public static void fillFile(String fileName, String name, String value) throws IOException {
        Path path = Paths.get(fileName);
        List<String> all = Files.readAllLines(path,StandardCharsets.UTF_8);
        System.out.println(" the path "+Paths.get(fileName));
        System.out.println(name + " :; "+ value);
        System.out.println("to write " + all.toString().replaceAll(", ", " ").substring(1, (all+"").replaceAll(", ", " ").length()-1)  + "\n" +  name + (name.endsWith(")")?"":" = ")+ value+ (name.endsWith(")")?"":";")+"\n } ddddddddddddddddddddddd");
        FileWriter test = new FileWriter(fileName,true);
        test.write(all.toString().replaceAll(", ", " ").substring(1, all.toString().replaceAll(", ", " ").length()-1) +  "\n" +  name + (name.endsWith(")")?"":" = ")+ value+ (name.endsWith(")")?"":";")+"\n }");
        //test.flush();
        test.close();
    }

另一个问题:还有其他简单的方法可以达到我的目标吗?

解决方案是 FileWriter 类的路径应该与 File.readAllLine() 使用的路径不同。
所以我们要创建一个临时文件,将其复制到想要的fileName文件中,然后我们删除临时文件
希望这会帮助需要它的人。正在运行!!!

public static void fillFile(String fileName, String name, String value) throws IOException {
        Path path = Paths.get(fileName);
        List<String> all = null;
        if (path.toFile().exists()) { 
            all = Files.readAllLines(path,StandardCharsets.UTF_8);}
        if(all!= null) System.out.println(path + " the size of "+ all.toArray(new String[all.size()])+"");
        Path path2 = Files.createTempFile(path.getParent(),"test-file", ".java");
        Files.write(path2, ((all+"").replaceAll(", ", "\n").replaceAll("\[", "").replaceAll("\]", "").substring(1, ((all+"").replaceAll(", ", " ").replaceAll("\[", "").replaceAll("\]", "")).length()-1) +  "\n" +  name + value+ "\n" +"}").getBytes());
        Files.copy(path2, path, StandardCopyOption.REPLACE_EXISTING);
        Files.deleteIfExists(path2);
    }