Reputation: 931
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();
}
I am trying to update a file "valS.txt" present where all my .java files are present .This code compiles but does not update anything . I think the path is not reachable . HELP!!
Upvotes: 1
Views: 108
Reputation: 9639
Assuming your Status array is not empty, this code will work but the file text file will be updated in the compiled/output directory
So the text file in the source directory will not be updated, but the one in the output directory will.
Also note that the constructor of FileWirter you are using will overwrite the content of the file so you should use the one with the append argument:
public FileWriter(String fileName, boolean append) throws IOException
EDIT : if you REALLY need to update a file in the src directory you could do it like, this.
Not really nice but this will work
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();
}
Upvotes: 0
Reputation: 2216
outputWriter = new BufferedWriter(new FileWriter(valS.txt));
Try that instead of: outputWriter = new BufferedWriter(new FileWriter(getClass().getResource("valS.txt").getFile()));
Upvotes: 1
Reputation: 2286
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));
Upvotes: 0