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;
}
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!