TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVA

Java BufferedWriter Examples: Write Strings to Text File

Use the BufferedWriter type to create a text file and write strings to it. Call the write and newLine methods.
BufferedWriter. This class helps us write Strings and characters to a file. We can write a String with write(). With newLine() we add a newline.
Arrays, substrings. With BufferedWriter we are not limited to Strings. We can write chars, ints, arrays and even substrings. We often pass a FileWriter to the BufferedWriter constructor.
First example. This program introduces the syntax for BufferedWriter. We create a FileWriter and pass an example path to it. This is the target text file.

Write: We call this method on the BufferedWriter. No newline is inserted afterwards. We can pass a string argument.

NewLine: This inserts a platform-specific newline to the file. Often we call this after a string to create a file with lines.

Close: This finishes the file writing operations. We cannot write any more to the file.

Java program that uses BufferedWriter, write, newLine import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class Program { public static void main(String[] args) throws IOException { // Create a BufferedWriter around a FileWriter. // ... Write to an output text file. BufferedWriter writer = new BufferedWriter(new FileWriter( "C:\\programs\\output.txt")); // Write these lines to the file. // ... We call newLine to insert a newline character. writer.write("CAT"); writer.newLine(); writer.write("DOG"); writer.newLine(); writer.write("BIRD"); writer.close(); } } Output file: output.txt CAT DOG BIRD
Write string array. This example writes an entire String array to a file. It specifies a newline after each String. So we write an array to lines in a file.
Java program that writes String array to file import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class Program { public static void main(String[] args) throws IOException { String[] array = new String[3]; array[0] = "100A"; array[1] = "200B"; array[2] = "300C"; // Create our BufferedWriter. BufferedWriter writer = new BufferedWriter(new FileWriter( "C:\\programs\\output.txt")); // Loop over the elements in the string array and write each line. for (String line : array) { writer.write(line); writer.newLine(); } writer.close(); } } Output file: output.txt 100A 200B 300C
Substrings, chars, ints. BufferedWriter handles more than strings. It can write just a part of a string—a substring (specified with a start index and length).

Char: To write a char, we must use the append method. The write method will not work—it treats chars as integers.

Int: With write we write integers. If we write the ASCII value 97 we see an "a" in the file.

Char array: Write can handle an entire char array. We can also specify just a range within a char array.

Char Arrays
Java program that writes substrings, chars, ints import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class Program { public static void main(String[] args) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter( "C:\\programs\\output.txt")); // Write the second two characters of this string. String value = "abcdefghi"; writer.write(value, 2, 2); writer.newLine(); // Append a character to the file. writer.append(value.charAt(1)); writer.newLine(); // Write an integer to the file. writer.write(97); writer.newLine(); // Write a character array. // ... A range of characters can be instead written. char[] array = value.toCharArray(); writer.write(array); // Close our writer. writer.close(); } } Output file: output.txt cd b a abcdefghi
IOException, stream closed. Often the BufferedWriter will throw exceptions. In this example, we get an IOException because we write to a file we had already closed.

Warning: Writing files, as with BufferedWriter, causes many errors. Often exception handling (try, catch) keywords are needed.

Exceptions
Java program that writes after close import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class Program { public static void main(String[] args) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter( "C:\\programs\\output.txt")); // Close the writer. writer.close(); // This will cause an exception. writer.write("X"); } } Output Exception in thread "main" java.io.IOException: Stream closed at java.io.BufferedWriter.ensureOpen(Unknown Source) at java.io.BufferedWriter.write(Unknown Source) at java.io.Writer.write(Unknown Source) at Program.main(Program.java:15)
Throws IOException. In the examples, we use the "throws IOException" notation on our main methods. This is required—BufferedReader can cause an error for many reasons.
With BufferedReader, and the FileWriter type as help, we write Strings to file with ease. We can form lines with the newLine method.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf