使用Java 7 API逐字节读取文件 [英] Using Java 7 API to read a file byte by byte

查看:115
本文介绍了使用Java 7 API逐字节读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我想用Java读取的2 GB文件(实际上是4个2gb文件)。所以Java 7中有一个新功能可以让我一次读取所有字节。

I have a 2 gb file I want to read in Java (actually four 2gb files). And so there's a new feature in Java 7 that can let me read all the bytes at once.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class reconstructor {

    public static void main(String[] args) throws IOException {

        Path p = Paths.get("test.txt");     
        for (int i = 0; i < 1; i++) {
            byte[] b = Files.readAllBytes(p);
            Files.write(p, b, StandardOpenOption.APPEND);
        }

    }

}



<这是一个愚蠢的程序,它将读取一个预先输入单个字节的文件,并连续读取该文件并将其读回的内容附加到同一文件中。现在显然,RAM不够大,一次读取2gb文件,更不用说其中四个了,所以我想知道是否有任何快速方法,不使用外部库(除非这是唯一的方法)阅读四个文件逐字节,以便RAM不会过载(否则我最终会出现Java堆错误)。

This is a dumb program that wil read a file with a single byte pre entered in it and continuously read that file and append what it read back onto the same file. Now obviously, the RAM is not big enough to read a 2gb file at one time, let alone four of them, so I was wondering if there was any quick way, without using external libraries (unless that is the only way) to read four files byte by byte so that the RAM does not get overloaded (otherwise I end up with a Java heap error).

推荐答案

阅读逐字节是另一种极端的解决方案,并且效率非常低。您应该只使用BufferedInputStream,并按块读取字节块。

Reading byte by byte is the other extreme solution, and will be very inefficient. You should simply use a BufferedInputStream, and read the bytes chunk by chunk.

阅读关于字节流的Java IO教程

这篇关于使用Java 7 API逐字节读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆