Read and Write to Text Files in Java

In this tutorial, nosotros show yous how to read from and write to text (or character) files using classes bachelor in the java.io packet. Outset, let'southward look at the unlike classes that are capable of reading and writing character streams.

1. Reader, InputStreamReader, FileReader and BufferedReader

Reader is the abstract class for reading grapheme streams. It implements the following cardinal methods:

  • read() : reads a single graphic symbol.
  • read(char[]) : reads an assortment of characters.
  • skip(long) : skips some characters.
  • shut() : closes the stream.

InputStreamReader is a bridge from byte streams to character streams. It converts bytes into characters using a specified charset. The charset tin can be default character encoding of the operating system, or can be specified explicitly when creating an InputStreamReader .

FileReader is a convenient grade for reading text files using the default character encoding of the operating system.

BufferedReader reads text from a graphic symbol stream with efficiency (characters are buffered to avoid oft reading from the underlying stream) and provides a convenient method for reading a line of text readLine() .

The following diagram show human relationship of these reader classes in the java.io package:

Reader Hierarchy

2. Writer, OutputStreamWriter, FileWriter and BufferedWriter

Author is the abstruse form for writing character streams. It implements the following key methods:

  • write(int) : writes a unmarried character.
  • write(char[]) : writes an assortment of characters.
  • write(String) : writes a string.
  • close() : closes the stream.

OutputStreamWriter is a span from byte streams to grapheme streams. Characters are encoded into bytes using a specified charset. The charset can be default character encoding of the operating system, or can be specified explicitly when creating an OutputStreamWriter .

FileWriter is a convenient class for writing text files using the default graphic symbol encoding of the operating system.

BufferedWriter writes text to a character stream with efficiency (characters, arrays and strings are buffered to avoid often writing to the underlying stream) and provides a convenient method for writing a line separator: newLine() .

The following diagram testify human relationship of these writer classes in the java.io package:

Writer Hierarchy

3. Grapheme Encoding and Charset

When constructing a reader or writer object, the default character encoding of the operating system is used (e.g. Cp1252 on Windows):

FileReader reader = new FileReader("MyFile.txt"); FileWriter writer = new FileWriter("YourFile.txt");

Then if we want to apply a specific charset, use an InputStreamReader or OutputStreamWriter instead. For example:

InputStreamReader reader = new InputStreamReader( 					new FileInputStream("MyFile.txt"), "UTF-xvi");

That creates a new reader with the Unicode character encoding UTF-sixteen.

And the following statement constructs a author with the UTF-8 encoding:

OutputStreamWriter writer = new OutputStreamWriter( 					new FileOutputStream("YourFile.txt"), "UTF-8");

In case nosotros desire to utilize a BufferedReader , just wrap the InputStreamReader within, for case:

InputStreamReader reader = new InputStreamReader( 		new FileInputStream("MyFile.txt"), "UTF-16");  BufferedReader bufReader = new BufferedReader(reader);

And for a BufferedWriter example:

OutputStreamWriter author = new OutputStreamWriter( 					new FileOutputStream("YourFile.txt"), "UTF-8");  BufferedWriter bufWriter = new BufferedWriter(writer);

Now, let'southward look at some complete examples.

4. Java Reading from Text File Example

The post-obit small program reads every single character from the file MyFile.txt and prints all the characters to the output panel:

package net.codejava.io;  import java.io.FileReader; import java.io.IOException;  /**  * This program demonstrates how to read characters from a text file.  * @writer world wide web.codejava.cyberspace  *  */ public class TextFileReadingExample1 {  	public static void main(String[] args) { 		try { 			FileReader reader = new FileReader("MyFile.txt"); 			int character;  			while ((character = reader.read()) != -one) { 				Organization.out.print((char) graphic symbol); 			} 			reader.shut();  		} catch (IOException e) { 			e.printStackTrace(); 		} 	}  }

The following case reads a text file with assumption that the encoding is UTF-16:

package net.codejava.io;  import java.io.FileInputStream; import java.io.IOException; import coffee.io.InputStreamReader;  /**  * This program demonstrates how to read characters from a text file using  * a specified charset.  * @writer www.codejava.net  *  */ public form TextFileReadingExample2 {  	public static void main(String[] args) { 		try { 			FileInputStream inputStream = new FileInputStream("MyFile.txt"); 			InputStreamReader reader = new InputStreamReader(inputStream, "UTF-xvi"); 			int character;  			while ((character = reader.read()) != -i) { 				System.out.print((char) character); 			} 			reader.close();  		} catch (IOException e) { 			e.printStackTrace(); 		} 	}  }

And the following example uses a BufferedReader to read a text file line past line (this is the most efficient and preferred mode):

package internet.codejava.io;  import coffee.io.BufferedReader; import java.io.FileReader; import coffee.io.IOException;  /**  * This programme demonstrates how to read characters from a text file  * using a BufferedReader for efficiency.  * @author www.codejava.net  *  */ public class TextFileReadingExample3 {  	public static void master(String[] args) { 		try { 			FileReader reader = new FileReader("MyFile.txt"); 			BufferedReader bufferedReader = new BufferedReader(reader);  			String line;  			while ((line = bufferedReader.readLine()) != null) { 				System.out.println(line); 			} 			reader.close();  		} grab (IOException eastward) { 			due east.printStackTrace(); 		} 	}  }

5. Java Writing to Text File Instance

In the following example, a FileWriter is used to write 2 words "Howdy Earth" and "Good Bye!" to a file named MyFile.txt:

parcel cyberspace.codejava.io;  import java.io.FileWriter; import java.io.IOException;  /**  * This programme demonstrates how to write characters to a text file.  * @writer www.codejava.internet  *  */ public class TextFileWritingExample1 {  	public static void primary(String[] args) { 		try { 			FileWriter writer = new FileWriter("MyFile.txt", true); 			author.write("Hello World"); 			writer.write("\r\n");	// write new line 			writer.write("Good Good day!"); 			author.close(); 		} catch (IOException e) { 			east.printStackTrace(); 		}  	}  }

Notation that, a writer uses default character encoding of the operating organisation by default. Information technology also creates a new file if not exits, or overwrites the existing ane. If y'all want to append text to an existing file, pass a boolean flag of true to constructor of the author form:

FileWriter writer = new FileWriter("MyFile.txt", true);

The following example uses a BufferedReader that wraps a FileReader to append text to an existing file:

package internet.codejava.io;  import coffee.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException;  /**  * This program demonstrates how to write characters to a text file  * using a BufferedReader for efficiency.  * @writer www.codejava.internet  *  */ public class TextFileWritingExample2 {  	public static void main(Cord[] args) { 		try { 			FileWriter writer = new FileWriter("MyFile.txt", true); 			BufferedWriter bufferedWriter = new BufferedWriter(writer);  			bufferedWriter.write("Hello Globe"); 			bufferedWriter.newLine(); 			bufferedWriter.write("See You Again!");  			bufferedWriter.close(); 		} catch (IOException east) { 			e.printStackTrace(); 		}  	}  }

This is the preferred fashion to write to text file considering the BufferedReader provides efficient way for writing grapheme streams.

And the following case specifies specific character encoding (UTF-xvi) when writing to the file:

package net.codejava.io;  import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import coffee.io.OutputStreamWriter;  /**  * This program demonstrates how to write characters to a text file using  * a specified charset.  * @author www.codejava.net  *  */ public class TextFileWritingExample3 {  	public static void main(String[] args) { 		try { 			FileOutputStream outputStream = new FileOutputStream("MyFile.txt"); 			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-xvi"); 			BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); 			 			bufferedWriter.write("Xin chào"); 			bufferedWriter.newLine(); 			bufferedWriter.write("Hẹn gặp lại!"); 			 			bufferedWriter.shut(); 		} catch (IOException e) { 			eastward.printStackTrace(); 		} 		 	} }

This program writes some Unicode string (Vietnamese) to the specified text file.

NOTE: From Java seven, you can use endeavor-with-resources statement to simplify the lawmaking of opening and closing the reader/writer. For example:

try (FileReader reader = new FileReader("MyFile.txt")) { 	int character;  	while ((character = reader.read()) != -i) { 		Organization.out.print((char) graphic symbol); 	} } catch (IOException e) { 	e.printStackTrace(); }

References:

  • Lesson: Bones I/O (The Coffee Tutorials)

Related File IO Tutorials:

  • How to Read and Write Binary Files in Java
  • How to read text file line by line in Java
  • Java IO FileReader and FileWriter Examples

Other Coffee File IO Tutorials:

  • How to list files and directories in a directory in Coffee
  • Java IO - Common File and Directory Operations Examples
  • Coffee Serialization Bones Example
  • Agreement Java Externalization with Examples
  • How to execute Operating System Commands in Java
  • three ways for reading user'south input from console in Coffee
  • File alter notification example with Watch Service API
  • Java Scanner Tutorial and Code Examples
  • How to compress files in ZIP format in Java
  • How to extract Nada file in Java

Virtually the Author:

Nam Ha Minh is certified Coffee programmer (SCJP and SCWCD). He started programming with Java in the time of Java one.4 and has been falling in beloved with Java since and so. Make friend with him on Facebook and watch his Java videos you lot YouTube.

Add together comment

Read and Write to Text Files in Java

Source: https://www.codejava.net/java-se/file-io/how-to-read-and-write-text-file-in-java

0 Response to "Read and Write to Text Files in Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel