Open and Read Text File on Java

In this tutorial, we show you lot how to read from and write to text (or character) files using classes available in the java.io packet. First, let's look at the dissimilar classes that are capable of reading and writing character streams.

1. Reader, InputStreamReader, FileReader and BufferedReader

Reader is the abstract class for reading character streams. Information technology implements the following central methods:

  • read() : reads a single character.
  • read(char[]) : reads an assortment 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 organisation, or can be specified explicitly when creating an InputStreamReader .

FileReader is a convenient class 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 frequently reading from the underlying stream) and provides a user-friendly method for reading a line of text readLine() .

The post-obit diagram show relationship of these reader classes in the java.io package:

Reader Hierarchy

2. Author, OutputStreamWriter, FileWriter and BufferedWriter

Writer is the abstract grade for writing character streams. It implements the following fundamental methods:

  • write(int) : writes a unmarried character.
  • write(char[]) : writes an array of characters.
  • write(String) : writes a cord.
  • shut() : closes the stream.

OutputStreamWriter is a bridge from byte streams to grapheme streams. Characters are encoded into bytes using a specified charset. The charset can exist 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 character encoding of the operating arrangement.

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

The following diagram prove human relationship of these writer classes in the coffee.io packet:

Writer Hierarchy

3. Character Encoding and Charset

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

FileReader reader = new FileReader("MyFile.txt"); FileWriter writer = 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 character encoding UTF-sixteen.

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 employ a BufferedReader , just wrap the InputStreamReader within, for example:

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

And for a BufferedWriter example:

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

Now, permit's look at some complete examples.

4. Java Reading from Text File Instance

The following small programme reads every single character from the file MyFile.txt and prints all the characters to the output console:

package internet.codejava.io;  import java.io.FileReader; import java.io.IOException;  /**  * This programme demonstrates how to read characters from a text file.  * @author world wide web.codejava.net  *  */ public grade TextFileReadingExample1 {  	public static void main(Cord[] args) { 		endeavor { 			FileReader reader = new FileReader("MyFile.txt"); 			int graphic symbol;  			while ((graphic symbol = reader.read()) != -1) { 				Organisation.out.print((char) grapheme); 			} 			reader.shut();  		} catch (IOException e) { 			e.printStackTrace(); 		} 	}  }

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

package 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 world wide web.codejava.internet  *  */ public form TextFileReadingExample2 {  	public static void principal(String[] args) { 		try { 			FileInputStream inputStream = new FileInputStream("MyFile.txt"); 			InputStreamReader reader = new InputStreamReader(inputStream, "UTF-16"); 			int character;  			while ((character = reader.read()) != -ane) { 				Arrangement.out.print((char) grapheme); 			} 			reader.close();  		} catch (IOException eastward) { 			e.printStackTrace(); 		} 	}  }

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

package net.codejava.io;  import coffee.io.BufferedReader; import java.io.FileReader; import java.io.IOException;  /**  * This program demonstrates how to read characters from a text file  * using a BufferedReader for efficiency.  * @writer world wide web.codejava.net  *  */ public form 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()) != aught) { 				Arrangement.out.println(line); 			} 			reader.shut();  		} catch (IOException e) { 			e.printStackTrace(); 		} 	}  }

five. Java Writing to Text File Example

In the following case, a FileWriter is used to write two words "How-do-you-do Globe" and "Good Bye!" to a file named MyFile.txt:

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

Annotation that, a writer uses default graphic symbol encoding of the operating arrangement by default. Information technology also creates a new file if not exits, or overwrites the existing ane. If yous want to append text to an existing file, laissez passer a boolean flag of true to constructor of the writer class:

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

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

packet net.codejava.io;  import java.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.  * @author world wide web.codejava.internet  *  */ public class TextFileWritingExample2 {  	public static void chief(String[] args) { 		try { 			FileWriter writer = new FileWriter("MyFile.txt", true); 			BufferedWriter bufferedWriter = new BufferedWriter(writer);  			bufferedWriter.write("Hello World"); 			bufferedWriter.newLine(); 			bufferedWriter.write("Run into You Once more!");  			bufferedWriter.close(); 		} catch (IOException eastward) { 			e.printStackTrace(); 		}  	}  }

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

And the following example specifies specific character 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 plan demonstrates how to write characters to a text file using  * a specified charset.  * @author www.codejava.cyberspace  *  */ public class TextFileWritingExample3 {  	public static void main(String[] args) { 		try { 			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 string (Vietnamese) to the specified text file.

NOTE: From Coffee seven, y'all tin can utilise try-with-resource argument to simplify the code of opening and closing the reader/writer. For example:

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

References:

  • Lesson: Basic I/O (The Java Tutorials)

Related File IO Tutorials:

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

Other Java File IO Tutorials:

  • How to listing files and directories in a directory in Java
  • Java IO - Common File and Directory Operations Examples
  • Java Serialization Basic Instance
  • Understanding Java Externalization with Examples
  • How to execute Operating System Commands in Java
  • 3 ways for reading user'due south input from panel in Coffee
  • File alter notification example with Picket Service API
  • Java Scanner Tutorial and Lawmaking Examples
  • How to compress files in ZIP format in Java
  • How to excerpt ZIP file in Java

About the Author:

Nam Ha Minh is certified Java developer (SCJP and SCWCD). He started programming with Java in the time of Java i.4 and has been falling in dear with Java since then. Brand friend with him on Facebook and lookout his Coffee videos you YouTube.

Add together comment

porterhille1980.blogspot.com

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

0 Response to "Open and Read Text File on Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel