In Java, you can get the size of a file using the length() method of the File class.
Here's an example of how to get the size of a file in Java:
import java.io.File;
public class GetFileSizeExample {
public static void main(String[] args) {
String fileName = "example.txt";
File file = new File(fileName);
if (file.exists()) {
long fileSize = file.length();
System.out.println("File size in bytes: " + fileSize);
} else {
System.out.println("File does not exist.");
}
}
}
In this example, we create a new File object representing the file we want to get the size of, using the filename "example.txt". We then call the exists() method on the File object to check if the file exists. If the file exists, we call the length() method on the File object, which returns the size of the file in bytes.
We then print the size of the file to the console. If the file does not exist, we print a message indicating that the file does not exist.
It's important to note that when getting the size of a file in Java, the size is returned in bytes. If you want to convert the size to another unit, such as kilobytes or megabytes, you can divide the size by the appropriate factor. For example, to get the size of the file in kilobytes, you can divide the size by 1024.