我如何从一个非常大的文件中读取字节?然后将它们存储在一个字符串中,例如.pdf .zip .xlsx 文件

How can i read bytes from a very heavy file? then store store them in a String e.g. .pdf .zip .xlsx files

我使用 java.nio.file.Files 库,该方法仅在我选择小文件(如 txt、docx、"pdf but ONLY with a tiny size")时有效,有时会延迟几分钟。但是,如果我选择一个带有任何扩展名的非常大的文件,或者只是带有更多 "complex" 扩展名(如 .exe、.pptx、.zip、.rar 等),程序冲突...如果你给我一个与 FileInputStreamFiles 具有相同功能的最新库的名称,那可能会很棒只是因为我认为问题是库不能支持大尺寸或也许是一个能解决我的问题的聪明的巫师。非常感谢¡

按照我使用的方法:

private void readBytes(){
    try{
        boolean completed=false;
        File file=null;
        JFileChooser chooser=new JFileChooser();
        if(chooser.showOpenDialog(this)==JFileChooser.APPROVE_OPTION){
            file=new File(chooser.getSelectedFile().getAbsoluteFile().getPath());
            byte[]bytes=Files.readAllBytes(file.getAbsoluteFile().toPath());
            String output="File size: "+file.length()+" bytes\n\n";
            for(int i=0;i<bytes.length;i++){
                output+=bytes[i]+"  ";
                if(i!=0){                        
                    if(i%10==0)output+="\n";
                }
                if(i==(int)file.length()-1)completed=true;
            }
            if(completed)JOptionPane.showMessageDialog(this, "The reading has completed and the file size is: "+file.length()+" bytes");
            else JOptionPane.showMessageDialog(this, "The reading has not completed","Error",0);
            jTextArea1.setText(output);
        }
    }
    catch(Exception ex){}
}

Files.readAllBytes 不推荐用于大文件,因为它会加载到内存中。 也许你可以使用 MappedByteBuffer。

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class ReadFileWithMappedByteBuffer 
{
    public static void main(String[] args) throws IOException 
    {
        RandomAccessFile aFile = new RandomAccessFile
                ("test.txt", "r");
        FileChannel inChannel = aFile.getChannel();
        MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
        buffer.load();  
        for (int i = 0; i < buffer.limit(); i++)
        {
            System.out.print((char) buffer.get());
        }
        buffer.clear(); // do something with the data and clear/compact it.
        inChannel.close();
        aFile.close();
    }
}

更多选项请参考http://howtodoinjava.com/java-7/nio/3-ways-to-read-files-using-java-nio/