Reading Files in Java Charater by Charater Example

In this tutorial, we show y'all how to read from and write to text (or character) files using classes bachelor in the java.io package. First, let'south look at the dissimilar classes that are capable of reading and writing character streams.

ane. Reader, InputStreamReader, FileReader and BufferedReader

Reader is the abstract class for reading grapheme streams. It implements the post-obit fundamental methods:

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

InputStreamReader is a span 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 class for reading text files using the default character encoding of the operating system.

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

The following diagram testify human relationship of these reader classes in the coffee.io bundle:

Reader Hierarchy

ii. Writer, OutputStreamWriter, FileWriter and BufferedWriter

Writer is the abstract class for writing graphic symbol streams. It implements the post-obit cardinal methods:

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

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

FileWriter is a user-friendly form for writing text files using the default character encoding of the operating system.

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 show relationship of these author classes in the coffee.io package:

Writer Hierarchy

three. Character Encoding and Charset

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

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

So if we want to use a specific charset, apply 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 following statement constructs a writer with the UTF-viii encoding:

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

In instance nosotros want to use a BufferedReader , just wrap the InputStreamReader inside, for example:

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

And for a BufferedWriter instance:

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

Now, permit'south await at some consummate examples.

4. Coffee Reading from Text File Example

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

package net.codejava.io;  import java.io.FileReader; import java.io.IOException;  /**  * This program demonstrates how to read characters from a text file.  * @author world wide web.codejava.net  *  */ public class TextFileReadingExample1 {  	public static void main(Cord[] args) { 		endeavour { 			FileReader reader = new FileReader("MyFile.txt"); 			int character;  			while ((character = reader.read()) != -i) { 				System.out.print((char) character); 			} 			reader.shut();  		} grab (IOException e) { 			eastward.printStackTrace(); 		} 	}  }

The following case reads a text file with supposition that the encoding is UTF-xvi:

packet cyberspace.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.cyberspace  *  */ public form TextFileReadingExample2 {  	public static void main(String[] args) { 		attempt { 			FileInputStream inputStream = new FileInputStream("MyFile.txt"); 			InputStreamReader reader = new InputStreamReader(inputStream, "UTF-16"); 			int character;  			while ((character = reader.read()) != -1) { 				Organization.out.print((char) character); 			} 			reader.close();  		} catch (IOException e) { 			east.printStackTrace(); 		} 	}  }

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

package cyberspace.codejava.io;  import java.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.  * @author www.codejava.net  *  */ public class TextFileReadingExample3 {  	public static void chief(Cord[] args) { 		try { 			FileReader reader = new FileReader("MyFile.txt"); 			BufferedReader bufferedReader = new BufferedReader(reader);  			String line;  			while ((line = bufferedReader.readLine()) != nil) { 				System.out.println(line); 			} 			reader.shut();  		} catch (IOException e) { 			e.printStackTrace(); 		} 	}  }

v. Java Writing to Text File Example

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

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

Annotation that, a writer uses default character encoding of the operating organization past default. It too creates a new file if not exits, or overwrites the existing one. If yous want to suspend 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 example uses a BufferedReader that wraps a FileReader to append text to an existing file:

package 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 www.codejava.net  *  */ public class TextFileWritingExample2 {  	public static void main(Cord[] args) { 		endeavor { 			FileWriter writer = new FileWriter("MyFile.txt", true); 			BufferedWriter bufferedWriter = new BufferedWriter(author);  			bufferedWriter.write("Howdy World"); 			bufferedWriter.newLine(); 			bufferedWriter.write("Run into Y'all Again!");  			bufferedWriter.close(); 		} take hold of (IOException eastward) { 			e.printStackTrace(); 		}  	}  }

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

And the post-obit example 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 java.io.OutputStreamWriter;  /**  * This program demonstrates how to write characters to a text file using  * a specified charset.  * @writer world wide web.codejava.net  *  */ public class TextFileWritingExample3 {  	public static void principal(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(); 		} take hold of (IOException e) { 			east.printStackTrace(); 		} 		 	} }

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

NOTE: From Java seven, yous can use attempt-with-resources statement to simplify the code of opening and closing the reader/writer. For case:

effort (FileReader reader = new FileReader("MyFile.txt")) { 	int grapheme;  	while ((graphic symbol = reader.read()) != -1) { 		Arrangement.out.print((char) character); 	} } grab (IOException e) { 	e.printStackTrace(); }

References:

  • Lesson: Basic I/O (The Java 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 Java File IO Tutorials:

  • How to list files and directories in a directory in Coffee
  • Coffee IO - Common File and Directory Operations Examples
  • Java Serialization Basic Example
  • Understanding Java 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 instance with Watch 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 programmer (SCJP and SCWCD). He started programming with Java in the time of Java one.4 and has been falling in dear with Java since and so. Make friend with him on Facebook and watch his Java videos yous YouTube.

Add together comment

dickeywhoes1961.blogspot.com

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

Related Posts

0 Response to "Reading Files in Java Charater by Charater Example"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel