How to Write to and Read From a File in Java in the Same Run

In this tutorial, nosotros show you how to read from and write to text (or character) files using classes available in the java.io package. Starting time, allow's await at the different classes that are capable of reading and writing character streams.

1. Reader, InputStreamReader, FileReader and BufferedReader

Reader is the abstract form for reading character streams. It implements the post-obit fundamental 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 span from byte streams to character streams. Information technology converts bytes into characters using a specified charset. The charset tin can be default grapheme encoding of the operating arrangement, or can be specified explicitly when creating an InputStreamReader .

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

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

Reader Hierarchy

ii. Writer, OutputStreamWriter, FileWriter and BufferedWriter

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

  • write(int) : writes a unmarried grapheme.
  • write(char[]) : writes an array of characters.
  • write(String) : 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 can exist default graphic symbol 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 testify relationship of these writer classes in the coffee.io package:

Writer Hierarchy

3. Grapheme Encoding and Charset

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

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

And then if we want to utilize a specific charset, utilise 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 grapheme encoding UTF-16.

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

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

In case we want to use 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(writer);

Now, let's look at some complete examples.

iv. Java Reading from Text File Example

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

package net.codejava.io;  import coffee.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(String[] args) { 		try { 			FileReader reader = new FileReader("MyFile.txt"); 			int grapheme;  			while ((character = reader.read()) != -one) { 				System.out.print((char) character); 			} 			reader.close();  		} take hold of (IOException e) { 			e.printStackTrace(); 		} 	}  }

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

package net.codejava.io;  import coffee.io.FileInputStream; import coffee.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 master(String[] args) { 		effort { 			FileInputStream inputStream = new FileInputStream("MyFile.txt"); 			InputStreamReader reader = new InputStreamReader(inputStream, "UTF-sixteen"); 			int character;  			while ((character = reader.read()) != -1) { 				System.out.print((char) grapheme); 			} 			reader.close();  		} catch (IOException e) { 			east.printStackTrace(); 		} 	}  }

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

package net.codejava.io;  import java.io.BufferedReader; import java.io.FileReader; import coffee.io.IOException;  /**  * This program demonstrates how to read characters from a text file  * using a BufferedReader for efficiency.  * @author www.codejava.internet  *  */ public grade TextFileReadingExample3 {  	public static void main(String[] args) { 		endeavor { 			FileReader reader = new FileReader("MyFile.txt"); 			BufferedReader bufferedReader = new BufferedReader(reader);  			String line;  			while ((line = bufferedReader.readLine()) != nothing) { 				Organisation.out.println(line); 			} 			reader.shut();  		} catch (IOException e) { 			due east.printStackTrace(); 		} 	}  }

five. Java Writing to Text File Case

In the following instance, a FileWriter is used to write 2 words "Hello World" and "Skillful Bye!" to a file named MyFile.txt:

package net.codejava.io;  import java.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("Hello World"); 			writer.write("\r\n");	// write new line 			author.write("Good Bye!"); 			author.close(); 		} catch (IOException e) { 			east.printStackTrace(); 		}  	}  }

Notation that, a writer uses default character encoding of the operating system by default. Information technology also creates a new file if not exits, or overwrites the existing one. If you desire to suspend text to an existing file, laissez passer a boolean flag of truthful to constructor of the writer 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 cyberspace.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 primary(String[] args) { 		try { 			FileWriter writer = new FileWriter("MyFile.txt", truthful); 			BufferedWriter bufferedWriter = new BufferedWriter(writer);  			bufferedWriter.write("Hello World"); 			bufferedWriter.newLine(); 			bufferedWriter.write("See You Again!");  			bufferedWriter.shut(); 		} catch (IOException e) { 			east.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-16) when writing to the file:

package cyberspace.codejava.io;  import coffee.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 master(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 eastward) { 			eastward.printStackTrace(); 		} 		 	} }

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

Notation: From Java 7, you lot can apply try-with-resources statement to simplify the code of opening and closing the reader/writer. For instance:

try (FileReader reader = new FileReader("MyFile.txt")) { 	int character;  	while ((character = reader.read()) != -1) { 		System.out.impress((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 Java
  • How to read text file line by line in Coffee
  • 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 Case
  • Agreement Coffee Externalization with Examples
  • How to execute Operating Organisation Commands in Java
  • 3 means 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 shrink 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 Java in the fourth dimension of Java 1.4 and has been falling in honey with Java since then. Make friend with him on Facebook and lookout his Java videos you YouTube.

Add comment

butterssuress43.blogspot.com

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

0 Response to "How to Write to and Read From a File in Java in the Same Run"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel