Following example shows how to get file size in bytes using file.length() method in Java.
length
public long length()
Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory. Where it is required to distinguish an I/O exception from the case that 0L is returned, or where several attributes of the same file are required at the same time, then the Files.readAttributes method may be used.
Returns:
The length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist.Some operating systems may return 0L for pathnames denoting system-dependent entities such as devices or pipes.
Throws:
SecurityException - If a security manager exists and its
SecurityManager.checkRead(java.lang.String) method denies read access to the file
Sample Program
FileSize.java
Result
The above code will produce the following output if file exist in specified directory.
length
public long length()
Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory. Where it is required to distinguish an I/O exception from the case that 0L is returned, or where several attributes of the same file are required at the same time, then the Files.readAttributes method may be used.
Returns:
The length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist.Some operating systems may return 0L for pathnames denoting system-dependent entities such as devices or pipes.
Throws:
SecurityException - If a security manager exists and its
SecurityManager.checkRead(java.lang.String) method denies read access to the file
Sample Program
FileSize.java
package com.javatutorialcorner.file; import java.io.File; public class FileSize { public static void main(String[] args) { String path = "/home/annamalai/workspace/File/jtc.txt"; File jtcFile = new File(path); if (!jtcFile.exists() || !jtcFile.isFile()) { System.out.println("File doesn't exist"); } else { System.out.println("File size in Bytes : " + jtcFile.length()); } } }
Result
The above code will produce the following output if file exist in specified directory.
File size in Bytes : 4
0 comments:
Post a Comment