Skip to content Skip to sidebar Skip to footer

Read and Write Ini File in Java

In this tutorial, we show yous how to read from and write to text (or character) files using classes available in the java.io package. First, let'due south 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 grapheme streams. It implements the following fundamental methods:

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

InputStreamReader is a span from byte streams to grapheme streams. It converts bytes into characters using a specified charset. The charset tin exist default character encoding of the operating organization, or tin can be specified explicitly when creating an InputStreamReader .

FileReader is a convenient class for reading text files using the default graphic symbol encoding of the operating arrangement.

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 following diagram show relationship of these reader classes in the coffee.io packet:

Reader Hierarchy

2. Writer, OutputStreamWriter, FileWriter and BufferedWriter

Author is the abstruse class for writing graphic symbol streams. Information technology implements the following central methods:

  • write(int) : writes a single character.
  • write(char[]) : writes an array of characters.
  • write(Cord) : writes a cord.
  • close() : closes the stream.

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

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

BufferedWriter writes text to a grapheme 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 post-obit diagram show relationship of these author classes in the java.io package:

Writer Hierarchy

iii. Character Encoding and Charset

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

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

So if we want to apply a specific charset, employ 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 author with the UTF-8 encoding:

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

In case nosotros want to use a BufferedReader , merely 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 example:

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

Now, let'southward look at some consummate examples.

iv. Java Reading from Text File Case

The post-obit 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 coffee.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) { 		attempt { 			FileReader reader = new FileReader("MyFile.txt"); 			int character;  			while ((grapheme = reader.read()) != -ane) { 				Organization.out.print((char) character); 			} 			reader.close();  		} catch (IOException e) { 			e.printStackTrace(); 		} 	}  }

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

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

And the following instance uses a BufferedReader to read a text file line by line (this is the about efficient and preferred mode):

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

5. Java Writing to Text File Instance

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

packet net.codejava.io;  import coffee.io.FileWriter; import java.io.IOException;  /**  * This program demonstrates how to write characters to a text file.  * @author www.codejava.cyberspace  *  */ public grade TextFileWritingExample1 {  	public static void main(String[] args) { 		try { 			FileWriter writer = new FileWriter("MyFile.txt", true); 			writer.write("Hello World"); 			writer.write("\r\north");	// write new line 			writer.write("Good Cheerio!"); 			writer.close(); 		} catch (IOException due east) { 			e.printStackTrace(); 		}  	}  }

Notation that, a writer uses default character encoding of the operating organization by default. It 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 truthful to constructor of the author class:

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

The post-obit 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 coffee.io.IOException;  /**  * This plan 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(String[] args) { 		try { 			FileWriter writer = new FileWriter("MyFile.txt", truthful); 			BufferedWriter bufferedWriter = new BufferedWriter(writer);  			bufferedWriter.write("Hello Globe"); 			bufferedWriter.newLine(); 			bufferedWriter.write("See You Over again!");  			bufferedWriter.close(); 		} take hold of (IOException e) { 			e.printStackTrace(); 		}  	}  }

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

And the following example specifies specific character encoding (UTF-sixteen) 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 plan demonstrates how to write characters to a text file using  * a specified charset.  * @author www.codejava.internet  *  */ public class TextFileWritingExample3 {  	public static void main(Cord[] 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 due east) { 			e.printStackTrace(); 		} 		 	} }

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

Notation: From Coffee vii, you can use effort-with-resources statement to simplify the code of opening and closing the reader/author. For example:

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

References:

  • Lesson: Bones 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
  • Coffee IO FileReader and FileWriter Examples

Other Java File IO Tutorials:

  • How to list 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 Arrangement Commands in Java
  • 3 means for reading user'south input from panel in Java
  • File modify notification example with Watch Service API
  • Java Scanner Tutorial and Code Examples
  • How to compress files in Nil format in Java
  • How to excerpt ZIP file in Java

Nigh the Writer:

Nam Ha Minh is certified Java developer (SCJP and SCWCD). He started programming with Java in the fourth dimension of Coffee 1.iv and has been falling in love with Java since so. Make friend with him on Facebook and spotter his Java videos you YouTube.

Add annotate

piercelonly1952.blogspot.com

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

Post a Comment for "Read and Write Ini File in Java"