This snippet show how to write Strings to a file. It writes the String text as new line using the \n character. This class can be used to build Logger or write data into the file for storage.
<!--break-->
package com.livrona.snippets.io;
import java.io.FileOutputStream;
/**
* This snippet show how to write String to a file
*
* @author java4learners
*/
publicclass SimpleFileWriter {
private FileOutputStream fos;
private String fileName;
/**
* Store the filename
*
* @param fileName
*/
public SimpleFileWriter(String fileName) {
this.fileName = fileName;
}
/**
* Open the File Stream
*
* @throws Exception
*/
publicvoid open() throws Exception {
fos =new FileOutputStream(fileName);
}
/**
* Write a given text o the file
*
* @param text
* @throws Exception
*/
publicvoid writeLine(String text) throws Exception {
// write the text
fos.write(text.getBytes());
// write the new line
fos.write("\n".getBytes());
}
/**
* Flush and close the stream
*
* @throws Exception
*/
publicvoid close() throws Exception {
fos.flush();
fos.close();
}
publicstaticvoid main(String[] args) {
if (args.length !=1) {
System.out
.println("Usage: java com.livrona.snippets.io.FileWriter ");
System.exit(0);
}
String dataFile = args[0];
System.out.println("File : "+ dataFile);
// write 3 lines to file
try {
SimpleFileWriter writer =new SimpleFileWriter(dataFile);
writer.writeLine("Hello");
writer.writeLine("This is in new line");
writer.writeLine("bye");
writer.close();
} catch (Exception e) {
System.out.println("Failed to write : "+ e.getMessage());
e.printStackTrace();
}
}
}