我正在使用java.nio.file.Files
库,只有当我选择微小的文件(例如 txt,docx,“pdf ,但只有小尺寸”)时,该方法才有效,并且有时只有一些几分钟的延迟。但是如果我选择一个带有任何扩展名的非常大的文件,或者仅仅使用更复杂的扩展名(如 .exe,.pptx,.zip,.rar 等),程序就会发生冲突。如果你给我一个与FileInputStream
和Files
具有相同功能的最新图书馆的名称,那可能会很棒,因为我认为问题在于图书馆不能支持大尺寸或也许是一个能解决我问题的聪明巫师。非常感谢
按照以下方法使用:
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){}
}
答案 0 :(得分:0)
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/了解更多选项