簡體   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