Frage

I have a JTextField in which the user has to enter file path separated by comma

I take the text field value into an array:

String[] filename = filename.split(","); // where filename is the jtextfield value

I need to check the size of each file in the array.

If the file size is more than 10 MB, I need to inform the user.

How to convert an array of file path to array of files and calculate the file size of each file in Java?

I tried using :

File[] files = new File[filename.length];    

for(int i=0;i < filename.length;i++){    
    long filesizeinbytes=files[i].length;    
    long filesizeinkb= filesizeinbytes/1024;    
    long filesizeinmb=filesizeinkb/1024;    
}
War es hilfreich?

Lösung

You forgot to initialize each element in the files array. It would throw a NPE.

long totalFileSizeOfAllFiles = 0;
for(int i=0;i < filename.length;i++){    
    files[i] = new File(filename[i]); // This is required.
    long filesizeinbytes=files[i].length(); // Also length is a method.
    totalFileSizeOfAllFiles+=filesizeinbytes; // To get the total size of all the files present.

P.S:- The assumption here is that each entry in the filename[] array is a proper absolute/relative path to each file under consideration!

Andere Tipps

seems there is something missing here where do you create the File object inside the array

File[] files = new File[filename.length];    
for(int i=0;i < filename.length;i++){    
    File f = new File(filename[i]);
    long filesizeinbytes=f.length();    
    long filesizeinkb= filesizeinbytes/1024;    
    long filesizeinmb=filesizeinkb/1024;    

}

for(String path:fileName){
File file=new File(path);

long fileSizeInBytes = file.length();
long fileSizeInKB = fileSizeInBytes / 1024;
long fileSizeInMB = fileSizeInKB / 1024;

if (fileSizeInMB > 10) {
 // code to iform user
}
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top