- Get total size of file in bytes [duplicate]
- 4 Answers 4
- Linked
- Related
- Hot Network Questions
- Class File
- Interoperability with java.nio.file package
- Java get file size
- Java get file size
- Java get file size using File class
- Get file size in java using FileChannel class
- Java get file size using Apache Commons IO FileUtils class
- How to get the size of a file in MB (Megabytes)?
- Kotlin Extension Solution
Get total size of file in bytes [duplicate]
This is not a duplicate answer. How to get a file size and how to get a file size efficiently are two different topics.
4 Answers 4
You can use the length() method on File which returns the size in bytes.
This is a perfect answer, and I know I have done a bunch of weird things to get this in the past to get the size of a file. Wish I knew about this a long time ago!
You don’t need FileInputStream to calculate file size, new File(path_to_file).length() is enough. Or, if you insist, use fileinputstream.getChannel().size() .
In hindsight, needing both Path and File might be quite verbose, @Swapnil’s answer might be more concise.
Note that Java 1.6 has been end of life for a while. Even 1.7 is effectively eol as of April 2015. I don’t think this being available in 1.7+ is a real issue.
I’m writing this in 2015, and Java 1.6 is still used (and maintained!) in production where I work. Legacy systems are common in the real world.
public static void main(String[] args) < try < File file = new File("test.txt"); System.out.println(file.length()); >catch (Exception e) < >>
Linked
Related
Hot Network Questions
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.19.43539
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Class File
The conversion of a pathname string to or from an abstract pathname is inherently system-dependent. When an abstract pathname is converted into a pathname string, each name is separated from the next by a single copy of the default separator character. The default name-separator character is defined by the system property file.separator , and is made available in the public static fields separator and separatorChar of this class. When a pathname string is converted into an abstract pathname, the names within it may be separated by the default name-separator character or by any other name-separator character that is supported by the underlying system.
A pathname, whether abstract or in string form, may be either absolute or relative. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir , and is typically the directory in which the Java virtual machine was invoked.
The parent of an abstract pathname may be obtained by invoking the getParent() method of this class and consists of the pathname’s prefix and each name in the pathname’s name sequence except for the last. Each directory’s absolute pathname is an ancestor of any File object with an absolute abstract pathname which begins with the directory’s absolute pathname. For example, the directory denoted by the abstract pathname «/usr» is an ancestor of the directory denoted by the pathname «/usr/local/bin» .
- For UNIX platforms, the prefix of an absolute pathname is always «/» . Relative pathnames have no prefix. The abstract pathname denoting the root directory has the prefix «/» and an empty name sequence.
- For Microsoft Windows platforms, the prefix of a pathname that contains a drive specifier consists of the drive letter followed by «:» and possibly followed by «\\» if the pathname is absolute. The prefix of a UNC pathname is «\\\\» ; the hostname and the share name are the first two names in the name sequence. A relative pathname that does not specify a drive has no prefix.
Instances of this class may or may not denote an actual file-system object such as a file or a directory. If it does denote such an object then that object resides in a partition. A partition is an operating system-specific portion of storage for a file system. A single storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may contain multiple partitions. The object, if any, will reside on the partition named by some ancestor of the absolute form of this pathname.
A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are collectively known as access permissions. The file system may have multiple sets of access permissions on a single object. For example, one set may apply to the object’s owner, and another may apply to all other users. The access permissions on an object may cause some methods in this class to fail.
Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.
Interoperability with java.nio.file package
The java.nio.file package defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems. This API may be used to overcome many of the limitations of the java.io.File class. The toPath method may be used to obtain a Path that uses the abstract path represented by a File object to locate a file. The resulting Path may be used with the Files class to provide more efficient and extensive access to additional file operations, file attributes, and I/O exceptions to help diagnose errors when an operation on a file fails.
Java get file size
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Java get file size
- Java get file size using File class
- Get file size in java using FileChannel class
- Java get file size using Apache Commons IO FileUtils class
Before we look into an example program to get file size, we have a sample pdf file with size 2969575 bytes.
Java get file size using File class
Java File length() method returns the file size in bytes. The return value is unspecified if this file denotes a directory. So before calling this method to get file size in java, make sure file exists and it’s not a directory. Below is a simple java get file size example program using File class.
package com.journaldev.getfilesize; import java.io.File; public class JavaGetFileSize < static final String FILE_NAME = "/Users/pankaj/Downloads/file.pdf"; public static void main(String[] args) < File file = new File(FILE_NAME); if (!file.exists() || !file.isFile()) return; System.out.println(getFileSizeBytes(file)); System.out.println(getFileSizeKiloBytes(file)); System.out.println(getFileSizeMegaBytes(file)); >private static String getFileSizeMegaBytes(File file) < return (double) file.length() / (1024 * 1024) + " mb"; >private static String getFileSizeKiloBytes(File file) < return (double) file.length() / 1024 + " kb"; >private static String getFileSizeBytes(File file) < return file.length() + " bytes"; >>
Get file size in java using FileChannel class
We can use FileChannel size() method to get file size in bytes.
package com.journaldev.getfilesize; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.Paths; public class JavaGetFileSizeUsingFileChannel < static final String FILE_NAME = "/Users/pankaj/Downloads/file.pdf"; public static void main(String[] args) < Path filePath = Paths.get(FILE_NAME); FileChannel fileChannel; try < fileChannel = FileChannel.open(filePath); long fileSize = fileChannel.size(); System.out.println(fileSize + " bytes"); fileChannel.close(); >catch (IOException e) < e.printStackTrace(); >> >
Java get file size using Apache Commons IO FileUtils class
If you are already using Apache Commons IO in your project, then you can use FileUtils sizeOf method to get file size in java.
package com.journaldev.getfilesize; import java.io.File; import org.apache.commons.io.FileUtils; public class JavaGetFileSizeUsingApacheCommonsIO < static final String FILE_NAME = "/Users/pankaj/Downloads/file.pdf"; public static void main(String[] args) < File file = new File(FILE_NAME); long fileSize = FileUtils.sizeOf(file); System.out.println(fileSize + " bytes"); >>
That’s all for java get file size programs.
You can checkout more Java IO examples from our GitHub Repository.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
How to get the size of a file in MB (Megabytes)?
Use the length() method of the File class to return the size of the file in bytes.
// Get file from file name File file = new File("U:\intranet_root\intranet\R1112B2.zip"); // Get length of file in bytes long fileSizeInBytes = file.length(); // Convert the bytes to Kilobytes (1 KB = 1024 Bytes) long fileSizeInKB = fileSizeInBytes / 1024; // Convert the KB to MegaBytes (1 MB = 1024 KBytes) long fileSizeInMB = fileSizeInKB / 1024; if (fileSizeInMB > 27)
You could combine the conversion into one step, but I’ve tried to fully illustrate the process.
jsfiddle.net/darkkyoun/3g71k6ho/16 I did a fiddle base on your code, so whoever need it, can use the fiddle to test it out
File file = new File("infilename"); // Get the number of bytes in the file long sizeInBytes = file.length(); //transform in MB long sizeInMb = sizeInBytes / (1024 * 1024);
public static String getStringSizeLengthFile(long size) < DecimalFormat df = new DecimalFormat("0.00"); float sizeKb = 1024.0f; float sizeMb = sizeKb * sizeKb; float sizeGb = sizeMb * sizeKb; float sizeTerra = sizeGb * sizeKb; if(size < sizeMb) return df.format(size / sizeKb)+ " Kb"; else if(size < sizeGb) return df.format(size / sizeMb) + " Mb"; else if(size < sizeTerra) return df.format(size / sizeGb) + " Gb"; return ""; >
Returns human readable file size from Bytes to Exabytes , rounding down to the boundary.
File fileObj = new File(filePathString); String fileSizeReadable = FileUtils.byteCountToDisplaySize(fileObj.length()); // output will be like 56 MB
file.length() will return you the length in bytes, then you divide that by 1048576, and now you’ve got megabytes!
You can retrieve the length of the file with File#length(), which will return a value in bytes, so you need to divide this by 1024*1024 to get its value in mb.
Since Java 7 you can use java.nio.file.Files.size(Path p) .
Path path = Paths.get("C:\\1.txt"); long expectedSizeInMB = 27; long expectedSizeInBytes = 1024 * 1024 * expectedSizeInMB; long sizeInBytes = -1; try < sizeInBytes = Files.size(path); >catch (IOException e) < System.err.println("Cannot get the size - " + e); return; >if (sizeInBytes > expectedSizeInBytes) < System.out.println("Bigger than " + expectedSizeInMB + " MB"); >else
You can do something like this:
public static String getSizeLabel(Integer size) < String cnt_size = "0"; double size_kb = size / 1024; double size_mb = size_kb / 1024; double size_gb = size_mb / 1024; if (Math.floor(size_gb) >0) < try < String[] snplit = String.valueOf((size_gb)).split("\\."); cnt_size = snplit[0] + "." + snplit[1].substring(0, 2) + "GB"; >catch (Exception e) < cnt_size = String.valueOf(Math.round(size_gb)) + "GB"; >> else if (Math.floor(size_mb) > 0) < try < String[] snplit = String.valueOf((size_mb)).split("\\."); cnt_size = snplit[0] + "." + snplit[1].substring(0, 2) + "MB"; >catch (Exception e) < cnt_size = String.valueOf(Math.round(size_mb)) + "MB"; >> else < cnt_size = String.valueOf(Math.round(size_kb)) + "KB"; >return cnt_size; >
Integer filesize = new File("path").length(); getSizeLabel(filesize) // Output 16.02MB
Kotlin Extension Solution
Add these somewhere, then call if (myFile.sizeInMb > 27.0) or whichever you need:
val File.size get() = if (!exists()) 0.0 else length().toDouble() val File.sizeInKb get() = size / 1024 val File.sizeInMb get() = sizeInKb / 1024 val File.sizeInGb get() = sizeInMb / 1024 val File.sizeInTb get() = sizeInGb / 1024
If you’d like to make working with a String or Uri easier, try adding these:
fun Uri.asFile(): File = File(toString()) fun String?.asUri(): Uri? < try < return Uri.parse(this) >catch (e: Exception) < >return null >
If you’d like to easily display the values as a string, these are simple wrappers. Feel free to customize the default decimals displayed
fun File.sizeStr(): String = size.toString() fun File.sizeStrInKb(decimals: Int = 0): String = "%.$f".format(sizeInKb) fun File.sizeStrInMb(decimals: Int = 0): String = "%.$f".format(sizeInMb) fun File.sizeStrInGb(decimals: Int = 0): String = "%.$f".format(sizeInGb) fun File.sizeStrWithBytes(): String = sizeStr() + "b" fun File.sizeStrWithKb(decimals: Int = 0): String = sizeStrInKb(decimals) + "Kb" fun File.sizeStrWithMb(decimals: Int = 0): String = sizeStrInMb(decimals) + "Mb" fun File.sizeStrWithGb(decimals: Int = 0): String = sizeStrInGb(decimals) + "Gb"