Hi,
hey I have just started with Java & want some help.
How to write to file java using bufferedwriter?
Thanks in advance.
Hi,
hey I have just started with Java & want some help.
How to write to file java using bufferedwriter?
Thanks in advance.
Writing to a File
File gets created if its not existing.
Code:try { BufferedWriter out = new BufferedWriter(new FileWriter("outfilename")); out.write("aString"); out.close(); } catch (IOException e) { }
Class BufferedWriter
java.lang.Object
== java.io.Writer
== java.io.BufferedWriter
public class BufferedWriter -- extends Writer
Write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example,
will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.Code:PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
Write text file
Code:import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.Writer; public class Main { public static void main(String[] args) throws Exception { Writer writer = null; String text = "This is a text file"; File file = new File("write.txt"); writer = new BufferedWriter(new FileWriter(file)); writer.write(text); writer.close(); } }
Bookmarks