Tuesday, May 10, 2011

Java Write To File using BufferedWriter

For writing data to a file, the class FileWriter and BufferedWriter are used.

FileWriter :

FileWriter is a subclass of OutputStreamWriter class that is used to write text (as opposed to binary data) to a file. You create a FileWriter by specifying the file to be written to, or optionally, when the data should be appended to the end of an existing file instead of overwriting that file. The FileWriter class creates an internal FileOutputStream to write bytes to the specified file

BufferedWriter :

The BufferedWriter class is used to write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays and strings.
The constructor of the FileWriter class takes the file name which has to be buffered by the BufferedWriter stream. The write( ) method of BufferedWriter class is used to create the file into specified directory.

Here again decorator pattern is used, where FileWriter object is decorated to BufferedWriter to carry out write operation.

public static String readString()
{
BufferedReader in ;
String str = String.Empty();
try{
in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter string to be input: ");
str = in.readLine();
}
return str;
}

public static boolean writeFile(String fileName)
{
boolean exist = file.createNewFile();
if (!exist)
{
System.out.println("File already exists.");
return exist;

}
else
{
FileWriter fstream = new FileWriter(file_name);
BufferedWriter out = new BufferedWriter(fstream);
out.write(readString());
out.close();
System.out.println("File created successfully.");
return exist;

}
}



See also how to append text file.

No comments:

Post a Comment

Chitika