Java File length() Method
Example
Write text to a file, then get the size of the file:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Hello World");
myWriter.close();
File myFile = new File("filename.txt");
System.out.println(myFile.length());
}
}
Definition and Usage
The length() method returns the size of a file, in bytes. One byte holds one simple character, like a letter or a space, so the text Hello World is 11 bytes.
It returns 0 if the file does not exist. For a directory, the value has no fixed meaning, so use this method only for files.
Syntax
public long length()
Parameter Values
None.
Technical Details
| Returns: | The size of the file in bytes, as a long. 0 if the file does not exist. |
|---|
Related Pages
❮ File Methods