2014-02-22 64 views
1
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文件。此代码编译但不更新任何内容。我认为路径不可达。帮帮我!!从java文件更新文本文件

+1

有没有错误?异常? – Keerthivasan

+0

没有更新文件:( – rick

+0

我认为这行“getClass()。getResource(”valS.txt“)。getFile()”有一些问题 – rick

回答

0

假设你的状态数组不为空,这段代码将工作,但该文件的文本文件将在编译/输出目录

所以在源目录中的文本文件,将不会更新更新,但输出目录中的那个将会。

还要注意的是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(); 
} 
+0

有没有办法在我的源代码目录中更新? – rick

+0

我没有看到另一种方式,而不是硬编码文件的路径 –

+0

我无法硬编码路径:-( – rick

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

outputWriter =新的BufferedWriter(新的FileWriter(valS.txt));

尝试使用它来代替: outputWriter = new BufferedWriter(new FileWriter(getClass()。getResource(“valS.txt”)。getFile()));