The InputStreamReader is a superclass of the FileReader class and has constructors that allow the conversion of streams. With this you can convert a byte stream into a character stream. This is useful when you want to write a binary file to a file.
When a string is passed, the file with the given name is opened for reading. If it does not exist, the constructor throws an exception of type FileNotFoundException.
To create an InputStreamReader, we must first import the java.io. package. Once we have imported the package, we can create the InputStreamReaderInputStreamReader as follows:
import java.io.InputStreamReader;
import java.io.FileInputStream;
FileInputStream <fis_name> = new FileInputStream("myFile.txt");
InputStreamReader <isr_name> = new InputStreamReader(<fis_name>);
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.IOException;
public class codevisionz {
public static void main(String[] args) throws IOException {
char[] arr = new char[100];
try {
FileInputStream file = new FileInputStream("myFile.txt");
InputStreamReader sr = new InputStreamReader(file);
sr.read(arr);
System.out.println("Content of myFile.txt:");
System.out.println(arr);
sr.close();
} catch (IOException e) {
System.out.println("Error reading file");
System.out.println(e.toString());
}
}
}
Content of myFile.txt:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.