Java InputStream to File Example

Filed Under: Java

Files can be read using Reader or Stream in java. The Reader is good to use for text data but to work with binary data you should use Stream. FileInputStream is used to open the stream to read data from file. Here we will convert InputStream to file in Java, we will use OutputStream to write the new file.

InputStream to File

InputStream to File, Java InputStream to File, convert InputStream to file in java

InputStreamToFile.java


package com.journaldev.files;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class InputStreamToFile {

    public static void main(String[] args) {
        try {
            InputStream is = new FileInputStream("/Users/pankaj/source.txt");
            
            OutputStream os = new FileOutputStream("/Users/pankaj/new_source.txt");
            
            byte[] buffer = new byte[1024];
            int bytesRead;
            //read from is to buffer
            while((bytesRead = is.read(buffer)) !=-1){
                os.write(buffer, 0, bytesRead);
            }
            is.close();
            //flush OutputStream to write any buffered data to file
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

That’s all for a simple example to convert InputStream to file in java.

Comments

  1. ranjeet says:

    hello sir, i have to a data file that looks like:

    WID2 2011/ 2/22 0: 7: 2.440 KERU BHZ CM6 164452 50.000000 0.10E+01 1.000 0 -1.0 0.0
    DAT2
    lfOVg7kEl+V6FTUEkFUIN1Cl9+1UF1TV+OM+B5l6UN9l+UO7TkEUNkPkRVLkTUEFIVIlG1V0l+kHV01l
    2kGkLAUJ8kK0V9lBLV+l6UKkPV-ULmAWDkT4FkMW7oFXP1nHYDnCVFBl4VPn0WQkIkPVElGVAlRUFUJk
    CHK2 49242946
    WID2 2011/ 2/22 0: 7: 2.440 KERU BHN CM6 164452 50.000000 0.10E+01 1.000 0 0.0 90.0
    DAT2
    md+Wa4XL2lPUOHUJl3AVCmHV3V9mDV1W-m4kNWGlJkJV8PNkNVFV+m00UQl7USULlGV5IlBW5lHQW3n5
    0o9VFY6rHYDVOo+VPGUPm+VQLlTWImSXLm4nBbLnLn6XFV3l5mNVSWOm2nCWKXLpBl3ZHl9lTkTVMYBq

    CHK2 27586464
    WID2 2011/ 2/22 0: 7: 2.440 KERU BHE CM6 164452 50.000000 0.10E+01 1.000 0 90.0 90.0
    DAT2
    WV2lzSm6V-UTlIUNkJV7l-9VLn0W73mLV8UPkElCUIW-TmNVEWDnCV4W-mFCULUPm9MYFoDkKY-lHl-k
    NWTl0mKWT+SlOV7W3nFUOW7m33UNl2V9kSUJ9lGXAnP2Y8oBV4UNl976VTn6UQX3nA3V08l0lDX2l1l8
    CHK2 35339819

    Here after WID2, Header starts and after DAT2 data starts and it end when CHK2 comes. then again same process stars for another data. it contains 3 data.
    could you please, give some idea to read it?

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages