How to convert FileInputStream to InputStream in java?

How to convert FileInputStream to InputStream in java?

In Java, FileInputStream is a specific type of InputStream used to read data from a file. Since FileInputStream is a subclass of InputStream, you can use it directly as an InputStream. There is no need to explicitly convert a FileInputStream to an InputStream.

Here's an example demonstrating that you can use a FileInputStream as an InputStream:

import java.io.*; public class FileInputStreamToInputStreamExample { public static void main(String[] args) { // Create a FileInputStream to read from a file FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream("example.txt"); // Use the FileInputStream as an InputStream InputStream inputStream = fileInputStream; // Now, you can use inputStream to read data from the file int data; while ((data = inputStream.read()) != -1) { System.out.print((char) data); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileInputStream != null) { fileInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } } 

In this example:

  1. We create a FileInputStream to read data from a file named "example.txt."

  2. We then assign the FileInputStream to an InputStream variable called inputStream. This assignment is valid because FileInputStream is a subclass of InputStream.

  3. We use the inputStream to read data from the file and print it to the console.

There's no need for an explicit conversion; you can simply use the FileInputStream wherever an InputStream is expected.


More Tags

nant flutter-form-builder gtk maxdate chatbot nouislider tflearn testcafe dbunit uvm

More Java Questions

More Chemistry Calculators

More Math Calculators

More Fitness-Health Calculators

More Electrochemistry Calculators