im using the java.nio.file.Files
library and the method works only when i choose tiny files (like txt, docx, "pdf but ONLY with a tiny size") and sometimes with a some minutes of delay. But if i choose a very large file with any extension or simply with a more "complex" extension (like .exe, .pptx, .zip, .rar, etc) the program clashes¡. it could be great if you give me the name of a up to date libray that has the same functionality as FileInputStream
and Files
just because i think the problem is that the library can't support large sizes or maybe a brilliant sorcerer who can solve my issue. Very Thanks¡
following the method im using:
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
is not recommended for large files as it loads into memory. May be you could use 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();
}
}
Please refer http://howtodoinjava.com/java-7/nio/3-ways-to-read-files-using-java-nio/ for more options
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments