Java filereader read all about it

Java File IO FileReader and FileWriter Examples

In Java, the FileReader and FileWriter classes are designed for reading and writing text files at low level, i.e. reading and writing a single character or an array of characters at once.

1. Creating a FileReader object

You can create a new object of the FileReader class by supplying the file path either as a String or a File object. For example:

try < FileReader reader1 = new FileReader("/path/to/yourfile1.txt"); File file = new File("/path/to/yourfile2.txt"); FileReader reader2 = new FileReader(file); // code to read… >catch (FileNotFoundException ex)

As you can see, these FileReader contructors throw FileNotFoundException if the file does not exist or is a directory.

2. Reading Characters from a File

  • int read() : reads a single character, and returns the character as an integer value.
  • int read(char[] cbuf) : reads characters to an array, and returns the number of characters read.
  • int read(char[] cbuf, int offset, int length) : reads characters to a portion of an array, and returns the number of characters read.
  • int read(CharBuffer target) : reads characters into a character buffer, and returns the number of characters added to the buffer.
Читайте также:  Java apps for my mobile

After the reading is finished, you should close the reader by calling its close() method. If you use the reader within a try-with-resources structure, the Java compiler will generate the close call for you.

The following code reads a text file character by character and prints the content of the file to the standard output:

try ( FileReader reader = new FileReader("FileReaderExamples.java") ) < int charRead = -1; while ((charRead = reader.read()) != -1) < System.out.print((char) charRead); >> catch (FileNotFoundException ex) < System.err.println("File not found error: " + ex); >catch (IOException ex) < System.err.println("I/O error: " + ex); >

3. Creating a FileWriter object

You can create a new object of the FileWriter class by supplying the file path either as a String or a File object, and specify whether to append data to the end of an existing file or write data from the beginning. For example:

As you can see, these FileWriter contructors throw IOException if an I/O error occurs, e.g. the file does exist but is a directory.

The following code creates a new FileWriter object to append data to an existing file:

4. Writing Characters to a File

The FileWriter class inherits the following write methods from its super classes Writer and OutputStreamWriter :

  • write(int c) : writes a single character.
  • write(char[] cbuf) : writes an array of characters.
  • write(char[] cbuf, int offset, int length) : writes a portion of an array of characters.
  • write(String str) : writes a String.
  • write(String str, int offset, int length) : writes a portion of a String.

After the writing is finished, you should close the writer by calling its close() method. If you use the writer within a try-with-resources structure, the writer is closed implicitly.

Let’s see an example. The following code opens a text file for writing a String, append to the end of the file if it already exists:

try ( FileWriter writer = new FileWriter(new File(«Notes.txt»), true); ) < writer.write("Java FileWriter Examples"); >catch (IOException ex)

5. Java FileReader and FileWriter Examples

The FileReader and FileWriter classes are usually used together. The following example copies content of a text file to another, character by character:

try ( FileReader reader = new FileReader(«Notes1.txt»); FileWriter writer = new FileWriter(«Notes2.txt»); ) < int charRead = -1; while ((charRead = reader.read()) != -1) < writer.write(charRead); >> catch (IOException ex)

Note that the FileReader and FileWriter classes are usually wrapped inside a BufferedReader and BufferedWriter for more efficiency.

API References:

Other Java File IO Tutorials:

About the Author:

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

Add comment

Comments

CodeJava.net shares Java tutorials, code examples and sample projects for programmers at all levels.
CodeJava.net is created and managed by Nam Ha Minh — a passionate programmer.

Copyright © 2012 — 2023 CodeJava.net, all rights reserved.

Источник

Java filereader read all about it

Reads text from character files using a default buffer size. Decoding from bytes to characters uses either a specified charset or the platform’s default charset. The FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream .

Field Summary

Fields declared in class java.io.Reader

Constructor Summary

Method Summary

Methods declared in class java.io.InputStreamReader

Methods declared in class java.io.Reader

Methods declared in class java.lang.Object

Constructor Detail

FileReader

public FileReader​(String fileName) throws FileNotFoundException

FileReader

public FileReader​(File file) throws FileNotFoundException

FileReader

FileReader

public FileReader​(String fileName, Charset charset) throws IOException

FileReader

public FileReader​(File file, Charset charset) throws IOException

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Java FileReader

Java FileReader class can be used to read data (stream of characters) from files. In this tutorial, we will learn about FileReader class, its constructors, methods and usages with the help of examples.

  • meant for reading streams of characters.
  • part of java.io package.
  • extends InputStreamReader class.
  • implements Closeable , AutoCloseable and Readable interfaces.
  • if not provided, it uses the platform’s default charset.
  • uses a default buffer size for reading the files.

To use the FileReader in the application, we must first import it from package java.io using the import statement. For creating the instance of FileReader , use one of its constructors.

String fileName = "c:\temp\test.txt"; FileReader input = new FileReader(fileName);
File file = new File("c:\temp\test.txt"); FileReader input = new FileReader(file);

Above both examples create the file reader instance with the default character encoding. To specify a different character encoding, we can pass the encoding information as Charset in the second argument to both constructors.

FileReader input = new FileReader(fileName, Charset.forName("UTF8")); //or FileReader input = new FileReader(file, Charset.forName("UTF8"));

Let us see a few examples of reading a file using the FileReader in Java.

3.1. Reading a Small Text File in char[]

In the given example, we are reading a text file. The file contains 3 small hello world messages. Here we are attempting to read the file in single read() operation so make sure you create a sufficiently large char[] to store all the content on the file.

This should be used only for small text files.

String fileName = "demo.txt"; try(FileReader fileReader = new FileReader(fileName)) < char[] a = new char[2048]; fileReader.read(a); //verify content //System.out.println(new String(a)); >

3.2. Reading a File One Character at a Time

In the given example, we are using the read() method which reads a single character from the file and returns it. When all the content of the file has been read, it returns -1 which indicates the end of the file.

String fileName = "demo.txt"; FileReader fileReader = new FileReader(fileName); try < int i; while((i = fileReader.read()) != -1) < System.out.print((char)i); >> finally

3.3. Reading a File Line by Line

FileReader does not directly support reading a file line by line. For this, we need to wrap the FileReader inside a BufferedReader instance which provides the method readLine() .

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class FileReaderExample < public static void main(String[] args) throws IOException < String fileName = "demo.txt"; BufferedReader br = new BufferedReader(new FileReader(fileName)); try < String line; while ((line = br.readLine()) != null) < System.out.println(line); >> finally < br.close(); >> >

Источник

Оцените статью