- Java inputstreamreader to file
- Java InputStreamReader
- Example 1: Reading a file using InputStreamReader
- Example 2: Java Read file char by char using InputStreamReader
- Java – Write an InputStream to a File
- 1. Overview
- Further reading:
- Java — InputStream to Reader
- Java — Convert File to InputStream
- Java InputStream to Byte Array and ByteBuffer
- 2. Convert Using Plain Java
- 3. Convert Using Guava
- 4. Convert Using Commons IO
Java inputstreamreader to file
- Introduction to Java
- The complete History of Java Programming Language
- C++ vs Java vs Python
- How to Download and Install Java for 64 bit machine?
- Setting up the environment in Java
- How to Download and Install Eclipse on Windows?
- JDK in Java
- How JVM Works – JVM Architecture?
- Differences between JDK, JRE and JVM
- Just In Time Compiler
- Difference between JIT and JVM in Java
- Difference between Byte Code and Machine Code
- How is Java platform independent?
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Java if statement with Examples
- Java if-else
- Java if-else-if ladder with Examples
- Loops in Java
- For Loop in Java
- Java while loop with Examples
- Java do-while loop with Examples
- For-each loop in Java
- Continue Statement in Java
- Break statement in Java
- Usage of Break keyword in Java
- return keyword in Java
- Object Oriented Programming (OOPs) Concept in Java
- Why Java is not a purely Object-Oriented Language?
- Classes and Objects in Java
- Naming Conventions in Java
- Java Methods
- Access Modifiers in Java
- Java Constructors
- Four Main Object Oriented Programming Concepts of Java
- Inheritance in Java
- Abstraction in Java
- Encapsulation in Java
- Polymorphism in Java
- Interfaces in Java
- ‘this’ reference in Java
Java InputStreamReader
The Java InputStreamReader class is often used to read characters from files (or network connections) where the bytes represents text. In this Java tutorial, we will learn about InputStreamReader class, its creation and initialization, and its methods which help in reading the data from the source.
1. InputStreamReader class
- It acts as a bridge between the byte stream to character stream. Using InputStreamReader , we can read any file in bytes and convert the bytes into chararctes of the desired charset.
- It is part of java.io package.
- It extends the abstract class Reader .
- It implements Closeable , AutoCloseable and Readable interfaces.
- It provides methods for reading the characters from the Stream.
2. Creating an InputStreamReader
As mentioned earlier, InputStreamReader reads a file using byte stream and convert to character strea. It means we have to first create a InputStream and then use this Reader to read characters from the stream.
In given below example, InputStreamReader will read the characters from the input stream fis , that in turn reads the bytes from the file data.txt .
To set the Charset information is optional. In that case, the system’s default charset will be used.
String file = "c:\temp\data.txt"; // Creates an InputStream FileInputStream fis = new FileInputStream(file); // Creates an InputStreamReader InputStreamReader isr = new InputStreamReader(fis);
3. Setting Character Encoding
If the read characters from stream are in a different encoding then pass the set the Charset information in InputStreamReader ‘s constructor.
String file = "c:\temp\data.txt"; FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF8"));
4. Closing the InputStreamReader
Call the inputStreamReader.close() method when we are done with reading from the stream. Or we can use the auto-closable feature of this class.
In the given example, try-with-resources feature will close the InputStreamReader and FileInputStream automatically when the try block is completely executed.
String file = "c:\temp\data.txt"; try (InputStreamReader input = new InputStreamReader(new FileInputStream(file))) < //Perform operations >
5. Java InputStreamReader Example
Lets see a few examples to read a file using the InputStreamReader in Java. In each example, we will read the file demo.txt .
hello world 1 hello world 2 hello world 3
Example 1: Reading a file using InputStreamReader
In the given example, we are reading all the content of the file demo.txt into a character array. We then print the read characters into the standard output.
We should use this technique for small files. Also do not forget to create a sufficiently large character array that can store all the characters from the file.
The read(char[]) method reads characters into the given array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.
import java.io.FileInputStream; import java.io.InputStreamReader; public class InputStreamReaderExample < public static void main(String[] args) < // Creates an array of character char[] array = new char[50]; try (InputStreamReader input = new InputStreamReader(new FileInputStream("demo.txt"))) < // Reads characters from the file input.read(array); System.out.println(array); >catch (Exception e) < e.getStackTrace(); >> >
hello world 1 hello world 2 hello world 3
Example 2: Java Read file char by char using InputStreamReader
In the given example, we will read the same file, but one character at a time. This can be used to read larger files as well.
import java.io.FileInputStream; import java.io.InputStreamReader; public class InputStreamReaderExample < public static void main(String[] args) < try (InputStreamReader input = new InputStreamReader(new FileInputStream("demo.txt"))) < int data = input.read(); while (data != -1) < //Do something with data e.g. append to StringBuffer System.out.print((char) data); data = input.read(); >> catch (Exception e) < e.getStackTrace(); >> >
hello world 1 hello world 2 hello world 3
Java – Write an InputStream to a File
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
In this quick tutorial, we’ll illustrate how to write an InputStream to a File. First we’ll use plain Java, then Guava, and finally the Apache Commons IO library.
This article is part of the “Java – Back to Basic” tutorial here on Baeldung.
Further reading:
Java — InputStream to Reader
Java — Convert File to InputStream
How to open an InputStream from a Java File — using plain Java, Guava and the Apache Commons IO library.
Java InputStream to Byte Array and ByteBuffer
2. Convert Using Plain Java
Let’s start with the Java solution:
@Test public void whenConvertingToFile_thenCorrect() throws IOException < Path path = Paths.get("src/test/resources/sample.txt"); byte[] buffer = java.nio.file.Files.readAllBytes(path); File targetFile = new File("src/test/resources/targetFile.tmp"); OutputStream outStream = new FileOutputStream(targetFile); outStream.write(buffer); IOUtils.closeQuietly(outStream); >
Note that in this example, the input stream has known and pre-determined data, such as a file on disk or an in-memory stream. As a result, we don’t need to do any bounds checking and we can, if memory allows, simply read it and write it in one go.
If the input stream is linked to an ongoing stream of data, like an HTTP response coming from an ongoing connection, then reading the entire stream once isn’t an option. In that case, we need to make sure we keep reading until we reach the end of the stream:
@Test public void whenConvertingInProgressToFile_thenCorrect() throws IOException < InputStream initialStream = new FileInputStream( new File("src/main/resources/sample.txt")); File targetFile = new File("src/main/resources/targetFile.tmp"); OutputStream outStream = new FileOutputStream(targetFile); byte[] buffer = new byte[8 * 1024]; int bytesRead; while ((bytesRead = initialStream.read(buffer)) != -1) < outStream.write(buffer, 0, bytesRead); >IOUtils.closeQuietly(initialStream); IOUtils.closeQuietly(outStream); >
Finally, here’s another simple way we can use Java 8 to do the same operation:
@Test public void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() throws IOException < InputStream initialStream = new FileInputStream( new File("src/main/resources/sample.txt")); File targetFile = new File("src/main/resources/targetFile.tmp"); java.nio.file.Files.copy( initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); IOUtils.closeQuietly(initialStream); >
3. Convert Using Guava
Next, let’s take a look at a simpler Guava based solution:
@Test public void whenConvertingInputStreamToFile_thenCorrect3() throws IOException < InputStream initialStream = new FileInputStream( new File("src/main/resources/sample.txt")); byte[] buffer = new byte[initialStream.available()]; initialStream.read(buffer); File targetFile = new File("src/main/resources/targetFile.tmp"); Files.write(buffer, targetFile); >
4. Convert Using Commons IO
Finally, here’s an even quicker solution with Apache Commons IO:
@Test public void whenConvertingInputStreamToFile_thenCorrect4() throws IOException < InputStream initialStream = FileUtils.openInputStream (new File("src/main/resources/sample.txt")); File targetFile = new File("src/main/resources/targetFile.tmp"); FileUtils.copyInputStreamToFile(initialStream, targetFile); >
And there we have it, 3 quick ways of writing the InputStream to a File.
The implementation of all these examples can be found in our GitHub project.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes: