Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Write text file Java

Tags:

java

file

file-io

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(); } 
like image 443
William Falcon Avatar asked Apr 02 '13 01:04

William Falcon


2 Answers

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

public class TestWriteFile {      public static void main(String[] args) {         BufferedWriter writer = null;         try {             //create a temporary file             String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());             File logFile = new File(timeLog);              // This will output the full path where the file will be written to...             System.out.println(logFile.getCanonicalPath());              writer = new BufferedWriter(new FileWriter(logFile));             writer.write("Hello world!");         } catch (Exception e) {             e.printStackTrace();         } finally {             try {                 // Close the writer regardless of what happens...                 writer.close();             } catch (Exception e) {             }         }     } } 

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:

writer = new BufferedWriter(new FileWriter(logFile, true)); 
like image 174
MadProgrammer Avatar answered Oct 14 '22 21:10

MadProgrammer


I would like to add a bit more to MadProgrammer's Answer.

In case of multiple line writing, when executing the command

writer.write(string); 

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,

System.out.println("\n"); 

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

String newline = System.getProperty("line.separator"); 

and then using the newline variable instead of "\n". This will get the output in the way you want it.

like image 27
Menezes Sousa Avatar answered Oct 14 '22 22:10

Menezes Sousa