java

How to convert InputStream to OutputStream in Java

To convert an InputStream into an OutputStream you have to write the bytes that are read from the InputStream into the OutputStream.

The bytes are written to “byte array buffer” with the read() method. The read() method returns the number of bytes read. If no bytes could be read, the value -1 is returned. In this case, the loop is broken.

The bytes written in the buffer can now be written in the OutputStream.

public static void convertStream1(InputStream from, OutputStream to) 
        throws IOException 
{
    byte[] buffer = new byte[1024];
    
    while (true) 
    {
        int bytesRead = from.read(buffer);
        
        if(bytesRead == -1)
        {
            break;
        }
        
        to.write(buffer, 0, bytesRead);
    }
}
 
A short form often used takes advantage of the fact that the result of an assignment is the value of the assigned variable.

public static void convertStream2(InputStream from, OutputStream to) 
        throws IOException 
{
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = from.read(buffer)) != -1) 
    {
         to.write(buffer, 0, bytesRead);
    }
}

Another possibility is to return the copied bytes as additional information when copying. For this purpose, the variable “totalBytesRead” is introduced, which adds up the bytes read in each case.

public static int convertStream3(InputStream from, OutputStream to) 
        throws IOException 
{
    byte[] buffer = new byte[1024];
    int bytesRead;
    int totalBytesRead = 0;
    
    while ((bytesRead = from.read(buffer)) != -1) 
    {
        to.write(buffer, 0, bytesRead);
        totalBytesRead += bytesRead;
    }
    
    return totalBytesRead;
}
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More

Leave a Reply

Your email address will not be published. Required fields are marked *