从java文件更新文本文件

时间:2014-02-22 07:55:15

标签: java file file-io ide

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(); 
}

我正在尝试更新存在所有.java文件的文件“valS.txt”。此代码编译但不更新任何内容。我认为路径无法到达。 HELP !!

3 个答案:

答案 0 :(得分:1)

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

尝试而不是: outputWriter = new BufferedWriter(new FileWriter(getClass()。getResource(“valS.txt”)。getFile()));

答案 1 :(得分:0)

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

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

另请注意,您正在使用的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();
}

答案 2 :(得分:0)

         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));