Reading a file using BufferedInputStream


Reading a file

Reading file using a BufferedInputStream generally faster than FileInputStream because it maintains an internal buffer to store bytes read from the underlying input stream.

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class FileReadingDemo {
	public static void main(String[] args) {
		String source = "hello.txt";
 
		try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source))) {
			byte data;
			while ((data = (byte) bis.read()) != -1) {
				System.out.println((char) data);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Writing a file using Channel and Buffer

To write data to a file using Channel we need to have the following steps:

  • First, we need to get an object of FileOutputStream
  • Acquire FileChannel calling the getChannel() method from the FileOutputStream
  • Create a ByteBuffer and then fill it with data
  • Then we have to call the flip() method of the ByteBuffer and pass it as an argument of the write() method of the FileChannel
  • Once we are done writing, we have to close the resource
import java.io.*;
import java.nio.*;
public class FileChannelWrite {
	public static void main(String[] args) {
		File outputFile = new File("sample.txt");
		String text = "I love Bangladesh.";
		try {
			FileOutputStream fos = new FileOutputStream(outputFile);
			FileChannel fileChannel = fos.getChannel();
			byte[] bytes = text.getBytes();
			ByteBuffer buffer = ByteBuffer.wrap(bytes);
			fileChannel.write(buffer);
			fileChannel.close();
		} catch (java.io.IOException e) {
			e.printStackTrace();
		}
	}
}

Writing a file using PrintStream

We can use PrintStream class to write a file. It has several methods that let you print any data type values. println() method appends a new line. Once we are done printing, we have to flush the PrintStream.

import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.time.LocalDate;
 
public class FileWritingDemo {
	public static void main(String[] args) {
		String destination = "file1.txt";
		try(PrintStream ps = new PrintStream(destination)){
			ps.println("Stackoverflow documentation seems fun.");
			ps.println();
			ps.println("I love Java!");
			ps.printf("Today is: %1$tm/%1$td/%1$tY", LocalDate.now());
 
			ps.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}

Iterating over a directory and filter by file extension

We can use PrintStream class to write a file. It has several methods that let you print any data type values. println() method appends a new line. Once we are done printing, we have to flush the PrintStream.

public void iterateAndFilter() throws IOException {
	Path dir = Paths.get("C:/foo/bar");
	PathMatcher imageFileMatcher =
	FileSystems.getDefault().getPathMatcher(
	"regex:.*(?i:jpg|jpeg|png|gif|bmp|jpe|jfif)");
 
	try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, entry -> imageFileMatcher.matches(entry.getFileName()))) {
		for (Path path : stream) {
			System.out.println(path.getFileName());
		}
	}
}

Accessing the contents of a ZIP file

The FileSystem API of Java 7 allows to read and add entries from or to a Zip file using the Java NIO file API in the same way as operating on any other filesystem.

The FileSystem is a resource that should be properly closed after use, therefore the try-with-resources block should be used.

import java.nio.file.FileSystems;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 
public class CustomZipFileHandling {
    public static void main(String[] args) {
        // Reading from an existing file
        Path customPathToZip = Paths.get("custom/path/to/data.zip");
        try (FileSystem customZipFs = FileSystems.newFileSystem(customPathToZip, null)) {
            Path customRoot = customZipFs.getPath("/");
            // Access the content of the zip file same as ordinary files
            // ... (your logic here)
        } catch (IOException ex) {
            ex.printStackTrace();
        }
 
        // Creating a new file
        Map<String, String> customEnv = new HashMap<>();
        customEnv.put("create", "true"); // Required for creating a new zip file
        customEnv.put("encoding", "UTF-8"); // Optional: default is UTF-8
        URI customUri = URI.create("jar:file:/custom/path/to/newFile.zip");
        try (FileSystem customZipfs = FileSystems.newFileSystem(customUri, customEnv)) {
            Path customNewFile = customZipfs.getPath("/newDocument.txt");
            // Writing to file
            Files.write(customNewFile, "Custom Hello World".getBytes());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Basic Programs