Skip to content

Instantly share code, notes, and snippets.

@pablohdzvizcarra
Created March 8, 2025 19:52
Show Gist options
  • Save pablohdzvizcarra/ca2be55a053e7b3486642da28ed0e7a1 to your computer and use it in GitHub Desktop.
Save pablohdzvizcarra/ca2be55a053e7b3486642da28ed0e7a1 to your computer and use it in GitHub Desktop.
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class Example4 {
public static void main(String[] args) {
String filePath = "data.txt";
int bufferSize = 100; // number of bytes
try (FileInputStream fis = new FileInputStream(filePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
byte[] buffer = new byte[bufferSize];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
// do something with each chunk
}
byte[] fileContent = baos.toByteArray();
System.out.println(new String(fileContent));
} catch (IOException e) {
System.out.println("An error ocurred reading the file: " + e.getMessage());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment