How to Get the size of a file in bytes
This code will print the size of a file in bytes to the console.
Code :
import java.io.File;
public class FileSize {
/**
* JavaProgrammingForums.com
*/
public long getFileSize(String filename) {
File file = new File(filename);
if (!file.exists() || !file.isFile()) {
System.out.println("File does not exist");
return -1;
}
// Code to get file size
return[B] file.length();[/B]
}
public static void main(String[] args) {
FileSize fs = new FileSize();
long size = fs.getFileSize("myFile.txt");
System.out.println("File size in bytes " + size);
}
}
Re: How to Get the size of a file in bytes
Great idea JavaPf. I would just like to post this link to the JavaDocs for the File object as there are alot of easy to follow functions that can give you information about files and folders. For this reason I feel it may be usefull to have a link to the JavaDocs. If anyone has a problem implementing one of the functions you are more than welcome to question us on how to use it.
File (Java 2 Platform SE v1.4.2)
Regards,
Chris