繁体   English   中英

如何从非常重的文件中读取字节? 然后将其存储在字符串中,例如.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

but ONLY with a tiny size") and sometimes with a some minutes of delay. 即时消息使用java.nio.file.Files库,该方法仅在我选择较小的文件(例如但仅具有很小的大小”)时有效,并且有时会延迟几分钟。 , etc) the program clashes¡. 但是,如果我选择一个带有任何扩展名的大文件,或者只是选择一个更“复杂”的扩展名(例如等),程序就会发生冲突。 如果您给我一个具有与FileInputStreamFiles相同功能的最新libray的名称,那可能很棒,因为我认为问题是该库无法支持大字体,或者可能是一个出色的巫师可以解决我的问题问题。 很感谢

遵循即时通讯使用的方法:

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/了解更多选项

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM