有 Java 编程相关的问题?

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

从java文件更新文本文件

public void updateF()throws Exception
{
    int i;
    BufferedWriter outputWriter = null;
    outputWriter = new BufferedWriter(new FileWriter(getClass().getResource("valS.txt").getFile()));
    for (i = 0; i < Status.length-1; i++) 
    {
            outputWriter.write(Status[i]+","); 
    }
    outputWriter.write(Status[i]);
    outputWriter.flush();  
    outputWriter.close(); 
}

我正在尝试更新一个文件“valS.txt”,其中显示了我的所有文件。存在java文件。此代码可编译但不更新任何内容。我认为这条路是走不到的。救命


共 (3) 个答案

  1. # 1 楼答案

    outputWriter=new BufferedWriter(new FileWriter(valS.txt))

    试着这样做,而不是: outputWriter=新的BufferedWriter(新的文件编写器(getClass())。getResource(“valS.txt”)。getFile())

  2. # 2 楼答案

             FileWritter, a character stream to write characters to file. By default, it will 
            replace all the  existing content with new content, however, when you specified a true (boolean)
            value as the second argument in FileWritter constructor, it will keep the existing content and 
            append the new content in the end of the file.
            fout = new FileWriter("filename.txt", true);
            the true is enabling append mode .
    
    write Like:
    BufferedWriter outputWriter = null;
    outputWriter = new BufferedWriter(new FileWriter(getClass().getResource("valS.txt").getFile(),true));
    
  3. # 3 楼答案

    假设您的状态数组不是空的,则此代码将起作用,但文件文本文件将在编译/输出目录中更新

    因此,源目录中的文本文件不会被更新,但输出目录中的文本文件会被更新

    还要注意,您正在使用的FileWirter的构造函数将覆盖文件的内容,因此您应该使用带有append参数的构造函数:

    public FileWriter(String fileName, boolean append) throws IOException 
    

    编辑:如果您确实需要更新src目录中的文件,可以这样做

    不是很好,但这会管用的

    public void updateF()throws Exception
    {
    
        String fileName = "valS.txt";
        File fileInClasses = new File(getClass().getResource(fileName).getFile());
        System.out.println(fileInClasses.getCanonicalPath());
        File f = fileInClasses;
        boolean outDir = false;
    
        // let's find the output directory
        while(!outDir){
            f = f.getParentFile();
            outDir = f.getName().equals("out");
        }
    
        // get the parent one more time
        f = f.getParentFile();
    
        // from there you should find back your file
        String totoPath = f.getPath()+"/src/com/brol/" + fileName;
        File totoFile = new File(totoPath);
    
        BufferedWriter outputWriter = null;
        outputWriter = new BufferedWriter(new FileWriter(totoFile, true));
        outputWriter.append("test");
        outputWriter.flush();
        outputWriter.close();
    }