try {
File file = new File("sample.txt");
FileWriter fw = new FileWriter(file,true);
fw.append('d');
fw.write(100);
fw.close();
} catch(IOException exp) {
exp.printStackTrace();
}
I am unable to append or write anything to the file.
But I could read the content from the file.
Is anything wrong with my code?
It sounds like you probably are writing to a file – but not the file you expect to. If no exceptions have been thrown (and swallowing an exception, just writing it to standard out, is rarely the right approach) then the file will exist somewhere.
It will be in whatever directory the code is running from – which may well not be the same as the directory containing the
sample.txtfile you’re reading. I suggest you explore the file system, and also check the Run Configuration in Eclipse to see what the working directory for the app will be.As an aside, you should be closing the writer in a
finallyblock so that it gets closed even if there’s an exception, like this:Obviously you can do this without Guava but it’ll make things a lot simpler – and not just here. If you’re using Java 7 you can make it even simpler with a try-with-resources statement.