从java文件更新文本文件 public void updateF()引发异常 { int i; BufferedWriter outputWriter=null; outputWriter=new BufferedWriter(新文件编写器(getClass().getResource(“valS.txt”).getFile()); 对于(i=0;i
我正在尝试更新一个文件“valS.txt”,其中包含我所有的.java文件。此代码可以编译,但不会更新任何内容。我认为这条路是走不到的。救命 假设您的状态数组不是空的,此代码将正常工作,但文件文本文件将在编译/输出目录中更新 因此,源目录中的文本文件不会被更新,但输出目录中的文本文件会被更新 还要注意,您正在使用的FileWirter的构造函数将覆盖文件的内容,因此您应该使用带有append参数的构造函数:从java文件更新文本文件 public void updateF()引发异常 { int i; BufferedWriter outputWriter=null; outputWriter=new BufferedWriter(新文件编写器(getClass().getResource(“valS.txt”).getFile()); 对于(i=0;i,java,file,file-io,ide,Java,File,File Io,Ide,我正在尝试更新一个文件“valS.txt”,其中包含我所有的.java文件。此代码可以编译,但不会更新任何内容。我认为这条路是走不到的。救命 假设您的状态数组不是空的,此代码将正常工作,但文件文本文件将在编译/输出目录中更新 因此,源目录中的文本文件不会被更新,但输出目录中的文本文件会被更新 还要注意,您正在使用的FileWirter的构造函数将覆盖文件的内容,因此您应该使用带有append参数的构造函数: public void updateF()throws Exception {
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();
}
编辑:如果您确实需要更新src目录中的文件,您可以这样做。不是很好,但这会管用的
public FileWriter(String fileName, boolean append) throws IOException
outputWriter=new BufferedWriter(new FileWriter(valS.txt)) 试着这样做,而不是:
outputWriter=new BufferedWriter(新文件编写器(getClass().getResource(“valS.txt”).getFile()) 有错误吗?异常?不更新文件:(我认为这行“getClass().getResource(“valS.txt”).getFile()”有一些问题什么是
Status[]
?它在哪里填充?您的valS.txt是否在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();
}
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));