Java File Input/Output Streams
In Java, file input/output streams are used for reading from and writing to files at the byte level. Input streams are used for reading data from a file, and output streams are used for writing data to a file.
FileInputStream:
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamExample {
public static void main(String[] args) {
// Specify the file path
String filePath = "path/to/your/file.txt";
try (FileInputStream inputStream = new FileInputStream(filePath)) {
int byteRead;
while ((byteRead = inputStream.read()) != -1) {
System.out.print((char) byteRead);
}
} catch (IOException e) {
System.out.println("Error reading from the file: " + e.getMessage());
}
}
}
FileOutputStream:
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamExample {
public static void main(String[] args) {
// Specify the file path
String filePath = "path/to/your/output.txt";
try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
// Write bytes to the file
String content = "Hello, this is written to the file!";
byte[] bytes = content.getBytes();
outputStream.write(bytes);
} catch (IOException e) {
System.out.println("Error writing to the file: " + e.getMessage());
}
}
}
Note:
Input/output streams in Java provide a way to work with files at a lower level, dealing with bytes. It is important
to handle exceptions properly and close stream resources in a try-with-resources block.