经典的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");
}
}