讀取文件 (NIO 四)

經典的I/O方式

這個示例展示了我們如何使用舊的I/O庫api讀取文本文件。它使用BufferedReader對象進行讀取。另一種方法是使用InputStream實現。

public class WithoutNIOExample {
	public static void main(String[] args) {
		String sCurrentLine = null;
		try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
			while ((sCurrentLine = br.readLine()) != null) {
				System.out.println(sCurrentLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

NIO方式

  • 讀取小文件

直接分配與文件大小一致的緩存區大小

public class ReadFileWithFileSizeBuffer {
	public static void main(String args[]) throws IOException {
		RandomAccessFile aFile = new RandomAccessFile("test.txt", "r");
		FileChannel inChannel = aFile.getChannel();
		int fileSize = (int) inChannel.size();
		ByteBuffer buffer = ByteBuffer.allocate(fileSize);
		inChannel.read(buffer);

		buffer.flip();
		for (int i = 0; i < fileSize; i++) {
			System.out.println(buffer.get());
		}
		inChannel.close();
		aFile.close();
	}
}
  • 讀取大文件

以固定大小緩衝區的塊讀取大文件

public class ReadFileWithFixedSizeBuffer {
	public static void main(String[] args) throws IOException {
		RandomAccessFile aFile = new RandomAccessFile("test.txt", "r");
		FileChannel inChannel = aFile.getChannel();
		System.out.println(inChannel.size());
		// 1K
		int times = 0;
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		while (inChannel.read(buffer) > 0) {
			buffer.flip();
			while (buffer.hasRemaining()) {
				buffer.get();
				times++;
			}
			buffer.clear();
		}
		inChannel.close();
		aFile.close();
		System.out.println(times);
		System.out.println("finish");
	}
}
  • 文件內存映射

更快的文件操作方式

public class ReadFileWithMappedByteBuffer {
	public static void main(String[] args) throws IOException {
		RandomAccessFile aFile = new RandomAccessFile("test.txt", "r");
		FileChannel inChannel = aFile.getChannel();
		System.out.println(inChannel.size());
		MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
		int times = 0;
		for (int i = 0; i < buffer.limit(); i++) {
			buffer.get();
			times++;
		}
		inChannel.close();
		aFile.close();
		System.out.println(times);
		System.out.println("finish");
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章