欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java读取大文件,超越内存限制

程序员文章站 2022-07-01 16:56:21
...
// 经典读取数据三(大文件)
	public static void readerFile3(String path) {
		int length = 0x8FFFFFF; // 128 Mb
		try {
			MappedByteBuffer out = new RandomAccessFile(path, "r").getChannel()
					.map(FileChannel.MapMode.READ_ONLY, 0, length);
			String result = "";
			for (int i = 0; i < 130; i++) {
				if (out.get(i) == 10) {
					result = "";
					System.out.println("换行了。");
				} else {
					result += (char) out.get(i);
				}
				if (out.get(i) == 13) {
					System.out.println(result + ":" + (result.trim().length()));
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}