Byte Stream Handling
Introduction to Byte Streams
Byte streams are fundamental for handling input and output operations in Java, providing efficient ways to read and write binary data.
Stream Types
graph TD
A[Byte Streams] --> B[Input Streams]
A --> C[Output Streams]
B --> D[FileInputStream]
B --> E[BufferedInputStream]
C --> F[FileOutputStream]
C --> G[BufferedOutputStream]
Stream Type |
Purpose |
Key Methods |
InputStream |
Reading bytes |
read(), close() |
OutputStream |
Writing bytes |
write(), flush(), close() |
File Byte Stream Operations
Reading Bytes from a File
public class ByteStreamReader {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("/tmp/sample.txt")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
System.out.println("Bytes read: " + bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Writing Bytes to a File
public class ByteStreamWriter {
public static void main(String[] args) {
byte[] data = "Hello, LabEx Byte Stream!".getBytes();
try (FileOutputStream fos = new FileOutputStream("/tmp/output.bin")) {
fos.write(data);
System.out.println("Bytes written successfully");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Advanced Byte Stream Techniques
Buffered Streams
public class BufferedByteDemo {
public static void main(String[] args) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("/tmp/large-file.bin"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("/tmp/output-buffered.bin"))) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
graph LR
A[Byte Stream Performance] --> B[Buffer Size]
A --> C[Stream Type]
A --> D[I/O Operations]
Ubuntu Practical Demonstration
To execute byte stream examples on Ubuntu 22.04:
## Create sample files
echo "Sample content" > /tmp/sample.txt
## Compile Java programs
javac ByteStreamReader.java
javac ByteStreamWriter.java
javac BufferedByteDemo.java
## Run demonstrations
java ByteStreamReader
java ByteStreamWriter
java BufferedByteDemo
Key Stream Handling Principles
- Use try-with-resources for automatic resource management
- Choose appropriate buffer sizes
- Handle exceptions carefully
- Close streams after use
LabEx Practical Insights
At LabEx, we emphasize mastering byte stream handling as a critical skill for efficient data processing and file manipulation in Java applications.