Important Java Concept

How to convert file to inputstream in Java

A File is a common storage unit in a computer that stores data and information.

In technical terms, Streams are used to move data from one place to another place. InputStreams are the streams that receive or read data.

All Streams are represented by the java.io (input-output) package.

Java Code To Convert File To InputStream

1. Using FileInputStream

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        FileInputStream fin = new FileInputStream("Path to myFile.txt");
        fin.close();
    }
}

Explanation:

Here we have used java.io package.  Then we used the fileInputStream to read data from a file in the form of sequence of bytes.

2. Using DataInputStream

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        File file = new File("Path to myFile.txt");
        InputStream fin = new DataInputStream(new FileInputStream(file));
        fin.close();
    }
}

3. Using Apache

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        File f1 = new File("Path to myFile.txt");
        InputStream fin = FileUtils.openInputStream(file);
    }
}

4. Using Guava

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException{
        File f1 = new File("Path to myFile.txt");
        InputStream fin = Files.asByteSource(f1).openStream();
    }

}

Explanation:

Guava is an open-source Java API library from google. Here ByteSource is used to read the bytes from the file and openStream is used to open a new input stream to read the byteSource.

Conclusion

In this article, we learned about the definition of the file, InputStream, and also about the packages used in the streams.

Do you want

Java Tutor?

Aniket Malik

Aniket Malik

ORACLE CERTIFIED JAVA TUTOR

🟢 Oracle Certified Java Expert

🟢 300 + ⭐ ⭐ ⭐ ⭐ ⭐

🟢 B.tech & M.tech in CSE

🟢 6+ Years of Teaching Experience

🟢 Worked as SE in Virtusa and Digidez

Do you want

Java Tutor?