Java Open a Text File for Reading

In this tutorial, we evidence y'all how to read from and write to text (or character) files using classes bachelor in the java.io package. First, allow'southward await at the different classes that are capable of reading and writing grapheme streams.

1. Reader, InputStreamReader, FileReader and BufferedReader

Reader is the abstract course for reading grapheme streams. It implements the following key methods:

  • read() : reads a single character.
  • read(char[]) : reads an array of characters.
  • skip(long) : skips some characters.
  • close() : closes the stream.

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

FileReader is a user-friendly class for reading text files using the default grapheme encoding of the operating arrangement.

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

The following diagram evidence relationship of these reader classes in the java.io packet:

Reader Hierarchy

2. Writer, OutputStreamWriter, FileWriter and BufferedWriter

Writer is the abstract class for writing graphic symbol streams. It implements the following fundamental methods:

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

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

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

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

The following diagram bear witness relationship of these writer classes in the java.io parcel:

Writer Hierarchy

three. Character Encoding and Charset

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

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

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

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

That creates a new reader with the Unicode graphic symbol encoding UTF-16.

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

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

In case we want to use a BufferedReader , just wrap the InputStreamReader inside, for example:

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

And for a BufferedWriter instance:

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

At present, allow's look at some complete examples.

4. Java Reading from Text File Example

The following modest program reads every single grapheme from the file MyFile.txt and prints all the characters to the output console:

package cyberspace.codejava.io;  import java.io.FileReader; import coffee.io.IOException;  /**  * This program demonstrates how to read characters from a text file.  * @author www.codejava.internet  *  */ public class TextFileReadingExample1 {  	public static void primary(Cord[] args) { 		effort { 			FileReader reader = new FileReader("MyFile.txt"); 			int character;  			while ((character = reader.read()) != -one) { 				System.out.print((char) graphic symbol); 			} 			reader.close();  		} catch (IOException e) { 			e.printStackTrace(); 		} 	}  }

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

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

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

packet net.codejava.io;  import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException;  /**  * This programme demonstrates how to read characters from a text file  * using a BufferedReader for efficiency.  * @author www.codejava.net  *  */ public course TextFileReadingExample3 {  	public static void main(String[] args) { 		try { 			FileReader reader = new FileReader("MyFile.txt"); 			BufferedReader bufferedReader = new BufferedReader(reader);  			String line;  			while ((line = bufferedReader.readLine()) != null) { 				Organisation.out.println(line); 			} 			reader.close();  		} catch (IOException e) { 			e.printStackTrace(); 		} 	}  }

5. Java Writing to Text File Case

In the following example, a FileWriter is used to write 2 words "How-do-you-do Earth" and "Skillful Bye!" to a file named MyFile.txt:

bundle net.codejava.io;  import java.io.FileWriter; import coffee.io.IOException;  /**  * This programme demonstrates how to write characters to a text file.  * @writer www.codejava.cyberspace  *  */ public form TextFileWritingExample1 {  	public static void chief(String[] args) { 		effort { 			FileWriter author = new FileWriter("MyFile.txt", true); 			writer.write("Howdy Earth"); 			writer.write("\r\n");	// write new line 			writer.write("Good Bye!"); 			writer.shut(); 		} catch (IOException e) { 			e.printStackTrace(); 		}  	}  }

Note that, a writer uses default graphic symbol encoding of the operating organisation past default. It too creates a new file if not exits, or overwrites the existing 1. If you desire to suspend text to an existing file, pass a boolean flag of true to constructor of the author class:

FileWriter author = new FileWriter("MyFile.txt", truthful);

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

packet cyberspace.codejava.io;  import java.io.BufferedWriter; import java.io.FileWriter; import coffee.io.IOException;  /**  * This program demonstrates how to write characters to a text file  * using a BufferedReader for efficiency.  * @author www.codejava.net  *  */ public course TextFileWritingExample2 {  	public static void master(String[] args) { 		try { 			FileWriter author = new FileWriter("MyFile.txt", true); 			BufferedWriter bufferedWriter = new BufferedWriter(writer);  			bufferedWriter.write("Hello World"); 			bufferedWriter.newLine(); 			bufferedWriter.write("Come across You Again!");  			bufferedWriter.close(); 		} catch (IOException e) { 			e.printStackTrace(); 		}  	}  }

This is the preferred way to write to text file because the BufferedReader provides efficient way for writing character streams.

And the following instance specifies specific graphic symbol encoding (UTF-16) when writing to the file:

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

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

NOTE: From Java 7, you tin use try-with-resource statement to simplify the code of opening and closing the reader/writer. For example:

try (FileReader reader = new FileReader("MyFile.txt")) { 	int character;  	while ((character = reader.read()) != -1) { 		System.out.print((char) character); 	} } catch (IOException e) { 	east.printStackTrace(); }

References:

  • Lesson: Basic 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 Java
  • Java IO - Common File and Directory Operations Examples
  • Java Serialization Basic Example
  • Understanding Coffee Externalization with Examples
  • How to execute Operating System Commands in Java
  • 3 ways for reading user's input from console in Java
  • File change notification example with Watch Service API
  • Java Scanner Tutorial and Code Examples
  • How to compress files in ZIP format in Java
  • How to extract ZIP file in Java

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Coffee in the time of Java ane.four and has been falling in dear with Coffee since then. Make friend with him on Facebook and sentinel his Java videos you YouTube.

Add annotate

smithhicip1967.blogspot.com

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

0 Response to "Java Open a Text File for Reading"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel