How to Read a File Seperated by Newline Java

In this tutorial, we prove you lot how to read from and write to text (or character) files using classes available in the coffee.io package. Commencement, permit'due south await at the dissimilar classes that are capable of reading and writing graphic symbol streams.

1. Reader, InputStreamReader, FileReader and BufferedReader

Reader is the abstract class for reading character 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 span from byte streams to character streams. Information technology converts bytes into characters using a specified charset. The charset can be default character encoding of the operating system, or can exist 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 grapheme stream with efficiency (characters are buffered to avert frequently reading from the underlying stream) and provides a convenient method for reading a line of text readLine() .

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

Reader Hierarchy

2. Writer, OutputStreamWriter, FileWriter and BufferedWriter

Writer is the abstract course 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 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 be default character encoding of the operating organization, or tin be specified explicitly when creating an OutputStreamWriter .

FileWriter is a convenient class for writing text files using the default graphic symbol encoding of the operating organization.

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

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

Writer Hierarchy

3. Character Encoding and Charset

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

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

So if we want to use 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 character encoding UTF-16.

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

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

In instance we want to employ a BufferedReader , merely wrap the InputStreamReader inside, for example:

InputStreamReader reader = new InputStreamReader( 		new FileInputStream("MyFile.txt"), "UTF-xvi");  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, let'due south look at some consummate examples.

4. Coffee Reading from Text File Example

The following small program reads every unmarried grapheme from the file MyFile.txt and prints all the characters to the output panel:

package internet.codejava.io;  import java.io.FileReader; import java.io.IOException;  /**  * This program demonstrates how to read characters from a text file.  * @writer world wide web.codejava.net  *  */ public class TextFileReadingExample1 {  	public static void main(Cord[] args) { 		attempt { 			FileReader reader = new FileReader("MyFile.txt"); 			int grapheme;  			while ((character = reader.read()) != -1) { 				System.out.impress((char) grapheme); 			} 			reader.close();  		} catch (IOException e) { 			due east.printStackTrace(); 		} 	}  }

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

package internet.codejava.io;  import java.io.FileInputStream; import coffee.io.IOException; import java.io.InputStreamReader;  /**  * This plan demonstrates how to read characters from a text file using  * a specified charset.  * @author www.codejava.internet  *  */ public course TextFileReadingExample2 {  	public static void main(String[] args) { 		try { 			FileInputStream inputStream = new FileInputStream("MyFile.txt"); 			InputStreamReader reader = new InputStreamReader(inputStream, "UTF-sixteen"); 			int character;  			while ((character = reader.read()) != -1) { 				Organisation.out.impress((char) character); 			} 			reader.close();  		} catch (IOException eastward) { 			e.printStackTrace(); 		} 	}  }

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

parcel net.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 main(Cord[] args) { 		effort { 			FileReader reader = new FileReader("MyFile.txt"); 			BufferedReader bufferedReader = new BufferedReader(reader);  			String line;  			while ((line = bufferedReader.readLine()) != null) { 				Organization.out.println(line); 			} 			reader.close();  		} catch (IOException eastward) { 			e.printStackTrace(); 		} 	}  }

5. Java Writing to Text File Example

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

bundle net.codejava.io;  import coffee.io.FileWriter; import java.io.IOException;  /**  * This program demonstrates how to write characters to a text file.  * @author world wide web.codejava.net  *  */ public class TextFileWritingExample1 {  	public static void main(String[] args) { 		try { 			FileWriter writer = new FileWriter("MyFile.txt", truthful); 			writer.write("Hello Earth"); 			author.write("\r\north");	// write new line 			writer.write("Good Bye!"); 			writer.shut(); 		} catch (IOException due east) { 			e.printStackTrace(); 		}  	}  }

Notation that, a writer uses default grapheme encoding of the operating organisation by default. It besides creates a new file if not exits, or overwrites the existing i. If yous desire to append text to an existing file, laissez passer a boolean flag of true to constructor of the writer course:

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

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

package net.codejava.io;  import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException;  /**  * This programme demonstrates how to write characters to a text file  * using a BufferedReader for efficiency.  * @author www.codejava.internet  *  */ public form TextFileWritingExample2 {  	public static void main(String[] args) { 		endeavor { 			FileWriter writer = new FileWriter("MyFile.txt", true); 			BufferedWriter bufferedWriter = new BufferedWriter(writer);  			bufferedWriter.write("How-do-you-do World"); 			bufferedWriter.newLine(); 			bufferedWriter.write("Run into You Over again!");  			bufferedWriter.shut(); 		} catch (IOException east) { 			eastward.printStackTrace(); 		}  	}  }

This is the preferred style to write to text file considering the BufferedReader provides efficient mode for writing grapheme streams.

And the following example specifies specific character encoding (UTF-16) when writing to the file:

package internet.codejava.io;  import java.io.BufferedWriter; import coffee.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 grade TextFileWritingExample3 {  	public static void principal(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(); 		} take hold of (IOException e) { 			due east.printStackTrace(); 		} 		 	} }

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

NOTE: From Java seven, you can utilise effort-with-resource statement to simplify the code of opening and endmost the reader/writer. For case:

endeavor (FileReader reader = new FileReader("MyFile.txt")) { 	int character;  	while ((character = reader.read()) != -1) { 		System.out.print((char) grapheme); 	} } catch (IOException e) { 	east.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
  • Coffee 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 Example
  • Understanding Java Externalization with Examples
  • How to execute Operating System Commands in Java
  • 3 ways for reading user's input from panel in Coffee
  • File alter notification example with Watch Service API
  • Java Scanner Tutorial and Lawmaking Examples
  • How to compress files in ZIP format in Coffee
  • How to excerpt Zippo file in Coffee

Nearly the Author:

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

Add together comment

gonzalezbegaind00.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 Read a File Seperated by Newline Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel