The following code does not produce a file (I can't see the file anywhere). What is missing?
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(
Calendar.getInstance().getTime());
File logFile=new File(timeLog);
BufferedWriter writer = new BufferedWriter(new FileWriter(logFile));
writer.write (string);
//Close writer
writer.close();
} catch(Exception e) {
e.printStackTrace();
}
It's not creating a file because you never actually created the file. You made an object for it. Creating an instance doesn't create the file.
You can do this to make a file:
You can do this to make a folder:
In java 7 can now do
and w.close will be done automatically
It does work with me. Make sure that you append ".txt" next to timeLog. I used it in a simple program opened with Netbeans and it writes the program in the main folder (where builder and src folders are).
I would like to add a bit more to MadProgrammer's Answer.
In case of multiple line writing, when executing the command
one may notice that the newline characters are omitted or skipped in the written file even though they appear during debugging or if the same text is printed onto the terminal with,
Thus, the whole text comes as one big chunk of text which is undesirable in most cases. The newline character can be dependent on the platform, so it is better to get this character from the java system properties using
and then using the newline variable instead of "\n". This will get the output in the way you want it.
You can try a Java Library. FileUtils, It has many functions that write to Files.
I think your expectations and reality don't match (but when do they ever ;))
Basically, where you think the file is written and where the file is actually written are not equal (hmmm, perhaps I should write an
if
statement ;))Also note that your example will overwrite any existing files. If you want to append the text to the file you should do the following instead: