Java Read and Insert Line Into Same File

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

1. Reader, InputStreamReader, FileReader and BufferedReader

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

  • read() : reads a single graphic symbol.
  • 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 exist default graphic symbol encoding of the operating system, or tin be specified explicitly when creating an InputStreamReader .

FileReader is a user-friendly course for reading text files using the default character encoding of the operating system.

BufferedReader reads text from a grapheme stream with efficiency (characters are buffered to avert oft reading from the underlying stream) and provides a user-friendly method for reading a line of text readLine() .

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

Reader Hierarchy

2. Writer, OutputStreamWriter, FileWriter and BufferedWriter

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

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

OutputStreamWriter is a span from byte streams to character 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 course 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 user-friendly method for writing a line separator: newLine() .

The post-obit diagram evidence relationship of these author classes in the coffee.io package:

Writer Hierarchy

3. Character Encoding and Charset

When amalgam 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");

So if we desire to utilise a specific charset, use an InputStreamReader or OutputStreamWriter instead. For instance:

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

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

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

OutputStreamWriter author = new OutputStreamWriter( 					new FileOutputStream("YourFile.txt"), "UTF-viii");

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

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

And for a BufferedWriter instance:

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

Now, allow'due south look at some consummate examples.

4. Java Reading from Text File Case

The following pocket-sized program reads every unmarried grapheme from the file MyFile.txt and prints all the characters to the output console:

package cyberspace.codejava.io;  import java.io.FileReader; import java.io.IOException;  /**  * This program demonstrates how to read characters from a text file.  * @author www.codejava.net  *  */ public class TextFileReadingExample1 {  	public static void main(String[] args) { 		try { 			FileReader reader = new FileReader("MyFile.txt"); 			int character;  			while ((graphic symbol = reader.read()) != -ane) { 				System.out.impress((char) character); 			} 			reader.shut();  		} grab (IOException east) { 			eastward.printStackTrace(); 		} 	}  }

The post-obit case reads a text file with supposition that the encoding is UTF-16:

package internet.codejava.io;  import java.io.FileInputStream; import java.io.IOException; import coffee.io.InputStreamReader;  /**  * This plan demonstrates how to read characters from a text file using  * a specified charset.  * @writer www.codejava.net  *  */ public form TextFileReadingExample2 {  	public static void principal(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.impress((char) character); 			} 			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 most efficient and preferred way):

bundle internet.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 world wide web.codejava.net  *  */ public course TextFileReadingExample3 {  	public static void main(Cord[] args) { 		effort { 			FileReader reader = new FileReader("MyFile.txt"); 			BufferedReader bufferedReader = new BufferedReader(reader);  			Cord line;  			while ((line = bufferedReader.readLine()) != null) { 				System.out.println(line); 			} 			reader.close();  		} catch (IOException e) { 			due east.printStackTrace(); 		} 	}  }

v. Java Writing to Text File Example

In the following case, a FileWriter is used to write two words "Hello World" and "Expert Bye!" to a file named MyFile.txt:

package cyberspace.codejava.io;  import java.io.FileWriter; import coffee.io.IOException;  /**  * This plan demonstrates how to write characters to a text file.  * @author world wide web.codejava.net  *  */ public form TextFileWritingExample1 {  	public static void main(String[] args) { 		try { 			FileWriter writer = new FileWriter("MyFile.txt", truthful); 			writer.write("Hello World"); 			writer.write("\r\n");	// write new line 			writer.write("Good Bye!"); 			writer.close(); 		} catch (IOException e) { 			e.printStackTrace(); 		}  	}  }

Note that, a writer uses default character encoding of the operating system by default. Information technology too creates a new file if not exits, or overwrites the existing one. If you want to append text to an existing file, pass a boolean flag of true to constructor of the writer class:

FileWriter author = 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 coffee.io.BufferedWriter; import coffee.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.cyberspace  *  */ public grade TextFileWritingExample2 {  	public static void main(Cord[] args) { 		try { 			FileWriter author = new FileWriter("MyFile.txt", true); 			BufferedWriter bufferedWriter = new BufferedWriter(writer);  			bufferedWriter.write("Hello World"); 			bufferedWriter.newLine(); 			bufferedWriter.write("See You lot Again!");  			bufferedWriter.close(); 		} catch (IOException e) { 			e.printStackTrace(); 		}  	}  }

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

And the following example specifies specific graphic symbol encoding (UTF-16) 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 programme 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-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) { 			e.printStackTrace(); 		} 		 	} }

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

Notation: From Coffee vii, you can employ try-with-resources argument to simplify the code of opening and closing the reader/writer. For example:

effort (FileReader reader = new FileReader("MyFile.txt")) { 	int grapheme;  	while ((character = reader.read()) != -i) { 		System.out.print((char) character); 	} } catch (IOException east) { 	e.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 Java File IO Tutorials:

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

Nearly the Author:

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

Add together comment

Java Read and Insert Line Into Same File

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

0 Response to "Java Read and Insert Line Into Same File"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel