Junior — Middle
What distinguishes FileInputStream from ByteArrayInputStream and in what situations is each used?
sobes.tech AI
Answer from AI
FileInputStream and ByteArrayInputStream are two classes in Java that implement InputStream, but differ in their data sources and use cases.
-
FileInputStream reads data from a file on disk. It opens a file descriptor and reads bytes directly from the file. It is used when working with large files or data stored outside of memory.
-
ByteArrayInputStream reads data from a byte array that is already in memory. This stream works with a buffer in RAM and does not require access to the file system.
Application:
FileInputStreamis suitable for reading large files when data needs to be obtained from an external source.ByteArrayInputStreamis convenient for testing, processing data already loaded into memory, or converting a byte array into a stream.
Example of using ByteArrayInputStream:
byte[] data = "Sample data".getBytes();
try (ByteArrayInputStream bais = new ByteArrayInputStream(data)) {
int ch;
while ((ch = bais.read()) != -1) {
System.out.print((char) ch);
}
}
Example of using FileInputStream:
try (FileInputStream fis = new FileInputStream("file.txt")) {
int ch;
while ((ch = fis.read()) != -1) {
System.out.print((char) ch);
}
}