How can I retrieve size of folder or file in Java?
asked Jan 27, 2010 at 19:44
2
java.io.File file = new java.io.File("myfile.txt");
file.length();
This returns the length of the file in bytes or 0
if the file does not exist. There is no built-in way to get the size of a folder, you are going to have to walk the directory tree recursively (using the listFiles()
method of a file object that represents a directory) and accumulate the directory size for yourself:
public static long folderSize(File directory) {
long length = 0;
for (File file : directory.listFiles()) {
if (file.isFile())
length += file.length();
else
length += folderSize(file);
}
return length;
}
WARNING: This method is not sufficiently robust for production use. directory.listFiles()
may return null
and cause a NullPointerException
. Also, it doesn’t consider symlinks and possibly has other failure modes. Use this method.
answered Jan 27, 2010 at 19:48
Tendayi MawusheTendayi Mawushe
25.4k6 gold badges50 silver badges57 bronze badges
4
Using java-7 nio api, calculating the folder size can be done a lot quicker.
Here is a ready to run example that is robust and won’t throw an exception. It will log directories it can’t enter or had trouble traversing. Symlinks are ignored, and concurrent modification of the directory won’t cause more trouble than necessary.
/**
* Attempts to calculate the size of a file or directory.
*
* <p>
* Since the operation is non-atomic, the returned value may be inaccurate.
* However, this method is quick and does its best.
*/
public static long size(Path path) {
final AtomicLong size = new AtomicLong(0);
try {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
size.addAndGet(attrs.size());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.out.println("skipped: " + file + " (" + exc + ")");
// Skip folders that can't be traversed
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
if (exc != null)
System.out.println("had trouble traversing: " + dir + " (" + exc + ")");
// Ignore errors traversing a folder
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
throw new AssertionError("walkFileTree will not throw IOException if the FileVisitor does not");
}
return size.get();
}
answered Nov 9, 2013 at 15:00
Aksel WillgertAksel Willgert
11.3k5 gold badges52 silver badges74 bronze badges
7
You need FileUtils#sizeOfDirectory(File)
from commons-io.
Note that you will need to manually check whether the file is a directory as the method throws an exception if a non-directory is passed to it.
WARNING: This method (as of commons-io 2.4) has a bug and may throw IllegalArgumentException
if the directory is concurrently modified.
answered Jul 1, 2012 at 20:31
yegor256yegor256
101k121 gold badges443 silver badges590 bronze badges
4
In Java 8:
long size = Files.walk(path).mapToLong( p -> p.toFile().length() ).sum();
It would be nicer to use Files::size
in the map step but it throws a checked exception.
UPDATE:
You should also be aware that this can throw an exception if some of the files/folders are not accessible. See this question and another solution using Guava.
answered Jul 14, 2014 at 10:18
AndrejsAndrejs
26.7k12 gold badges106 silver badges94 bronze badges
2
public static long getFolderSize(File dir) {
long size = 0;
for (File file : dir.listFiles()) {
if (file.isFile()) {
System.out.println(file.getName() + " " + file.length());
size += file.length();
}
else
size += getFolderSize(file);
}
return size;
}
answered Jan 27, 2010 at 19:49
VishalVishal
19.8k23 gold badges79 silver badges93 bronze badges
4
For Java 8 this is one right way to do it:
Files.walk(new File("D:/temp").toPath())
.map(f -> f.toFile())
.filter(f -> f.isFile())
.mapToLong(f -> f.length()).sum()
It is important to filter out all directories, because the length method isn’t guaranteed to be 0 for directories.
At least this code delivers the same size information like Windows Explorer itself does.
answered Feb 21, 2017 at 14:04
wumpzwumpz
8,1073 gold badges30 silver badges25 bronze badges
Here’s the best way to get a general File’s size (works for directory and non-directory):
public static long getSize(File file) {
long size;
if (file.isDirectory()) {
size = 0;
for (File child : file.listFiles()) {
size += getSize(child);
}
} else {
size = file.length();
}
return size;
}
Edit: Note that this is probably going to be a time-consuming operation. Don’t run it on the UI thread.
Also, here (taken from https://stackoverflow.com/a/5599842/1696171) is a nice way to get a user-readable String from the long returned:
public static String getReadableSize(long size) {
if(size <= 0) return "0";
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups))
+ " " + units[digitGroups];
}
answered Aug 22, 2014 at 4:52
Eric CochranEric Cochran
8,2905 gold badges50 silver badges90 bronze badges
File.length()
(Javadoc).
Note that this doesn’t work for directories, or is not guaranteed to work.
For a directory, what do you want? If it’s the total size of all files underneath it, you can recursively walk children using File.list()
and File.isDirectory()
and sum their sizes.
answered Jan 27, 2010 at 19:46
danbendanben
80.4k18 gold badges122 silver badges145 bronze badges
The File
object has a length
method:
f = new File("your/file/name");
f.length();
answered Jan 27, 2010 at 19:47
JesperEJesperE
63k21 gold badges138 silver badges195 bronze badges
If you want to use Java 8 NIO API, the following program will print the size, in bytes, of the directory it is located in.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathSize {
public static void main(String[] args) {
Path path = Paths.get(".");
long size = calculateSize(path);
System.out.println(size);
}
/**
* Returns the size, in bytes, of the specified <tt>path</tt>. If the given
* path is a regular file, trivially its size is returned. Else the path is
* a directory and its contents are recursively explored, returning the
* total sum of all files within the directory.
* <p>
* If an I/O exception occurs, it is suppressed within this method and
* <tt>0</tt> is returned as the size of the specified <tt>path</tt>.
*
* @param path path whose size is to be returned
* @return size of the specified path
*/
public static long calculateSize(Path path) {
try {
if (Files.isRegularFile(path)) {
return Files.size(path);
}
return Files.list(path).mapToLong(PathSize::calculateSize).sum();
} catch (IOException e) {
return 0L;
}
}
}
The calculateSize
method is universal for Path
objects, so it also works for files.
Note that if a file or directory is inaccessible, in this case the returned size of the path object will be 0
.
answered Mar 4, 2017 at 18:18
bobastibobasti
1,7781 gold badge20 silver badges28 bronze badges
- Works for Android and Java
- Works for both folders and files
- Checks for null pointer everywhere where needed
- Ignores symbolic link aka shortcuts
- Production ready!
Source code:
public long fileSize(File root) {
if(root == null){
return 0;
}
if(root.isFile()){
return root.length();
}
try {
if(isSymlink(root)){
return 0;
}
} catch (IOException e) {
e.printStackTrace();
return 0;
}
long length = 0;
File[] files = root.listFiles();
if(files == null){
return 0;
}
for (File file : files) {
length += fileSize(file);
}
return length;
}
private static boolean isSymlink(File file) throws IOException {
File canon;
if (file.getParent() == null) {
canon = file;
} else {
File canonDir = file.getParentFile().getCanonicalFile();
canon = new File(canonDir, file.getName());
}
return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
}
answered Oct 15, 2017 at 15:15
Ilya GazmanIlya Gazman
31.1k21 gold badges136 silver badges216 bronze badges
I’ve tested du -c <folderpath>
and is 2x faster than nio.Files or recursion
private static long getFolderSize(File folder){
if (folder != null && folder.exists() && folder.canRead()){
try {
Process p = new ProcessBuilder("du","-c",folder.getAbsolutePath()).start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String total = "";
for (String line; null != (line = r.readLine());)
total = line;
r.close();
p.waitFor();
if (total.length() > 0 && total.endsWith("total"))
return Long.parseLong(total.split("\s+")[0]) * 1024;
} catch (Exception ex) {
ex.printStackTrace();
}
}
return -1;
}
answered May 10, 2020 at 19:11
G DiasG Dias
891 silver badge3 bronze badges
for windows, using java.io this reccursive function is useful.
public static long folderSize(File directory) {
long length = 0;
if (directory.isFile())
length += directory.length();
else{
for (File file : directory.listFiles()) {
if (file.isFile())
length += file.length();
else
length += folderSize(file);
}
}
return length;
}
This is tested and working properly on my end.
answered Jul 17, 2019 at 11:30
private static long getFolderSize(Path folder) {
try {
return Files.walk(folder)
.filter(p -> p.toFile().isFile())
.mapToLong(p -> p.toFile().length())
.sum();
} catch (IOException e) {
e.printStackTrace();
return 0L;
}
answered Dec 24, 2019 at 8:18
2
public long folderSize (String directory)
{
File curDir = new File(directory);
long length = 0;
for(File f : curDir.listFiles())
{
if(f.isDirectory())
{
for ( File child : f.listFiles())
{
length = length + child.length();
}
System.out.println("Directory: " + f.getName() + " " + length + "kb");
}
else
{
length = f.length();
System.out.println("File: " + f.getName() + " " + length + "kb");
}
length = 0;
}
return length;
}
answered Oct 5, 2014 at 18:49
NicholasNicholas
3,4191 gold badge23 silver badges31 bronze badges
After lot of researching and looking into different solutions proposed here at StackOverflow. I finally decided to write my own solution. My purpose is to have no-throw mechanism because I don’t want to crash if the API is unable to fetch the folder size. This method is not suitable for mult-threaded scenario.
First of all I want to check for valid directories while traversing down the file system tree.
private static boolean isValidDir(File dir){
if (dir != null && dir.exists() && dir.isDirectory()){
return true;
}else{
return false;
}
}
Second I do not want my recursive call to go into symlinks (softlinks) and include the size in total aggregate.
public static boolean isSymlink(File file) throws IOException {
File canon;
if (file.getParent() == null) {
canon = file;
} else {
canon = new File(file.getParentFile().getCanonicalFile(),
file.getName());
}
return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
}
Finally my recursion based implementation to fetch the size of the specified directory. Notice the null check for dir.listFiles(). According to javadoc there is a possibility that this method can return null.
public static long getDirSize(File dir){
if (!isValidDir(dir))
return 0L;
File[] files = dir.listFiles();
//Guard for null pointer exception on files
if (files == null){
return 0L;
}else{
long size = 0L;
for(File file : files){
if (file.isFile()){
size += file.length();
}else{
try{
if (!isSymlink(file)) size += getDirSize(file);
}catch (IOException ioe){
//digest exception
}
}
}
return size;
}
}
Some cream on the cake, the API to get the size of the list Files (might be all of files and folder under root).
public static long getDirSize(List<File> files){
long size = 0L;
for(File file : files){
if (file.isDirectory()){
size += getDirSize(file);
} else {
size += file.length();
}
}
return size;
}
answered Jan 21, 2017 at 16:23
A.B.A.B.
1,5541 gold badge14 silver badges21 bronze badges
in linux if you want to sort directories then du -hs * | sort -h
answered Mar 31, 2017 at 19:27
Prem SPrem S
2173 silver badges8 bronze badges
You can use Apache Commons IO
to find the folder size easily.
If you are on maven, please add the following dependency in your pom.xml
file.
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
If not a fan of Maven, download the following jar and add it to the class path.
https://repo1.maven.org/maven2/commons-io/commons-io/2.6/commons-io-2.6.jar
public long getFolderSize() {
File folder = new File("src/test/resources");
long size = FileUtils.sizeOfDirectory(folder);
return size; // in bytes
}
To get file size via Commons IO,
File file = new File("ADD YOUR PATH TO FILE");
long fileSize = FileUtils.sizeOf(file);
System.out.println(fileSize); // bytes
It is also achievable via Google Guava
For Maven, add the following:
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.1-jre</version>
</dependency>
If not using Maven, add the following to class path
https://repo1.maven.org/maven2/com/google/guava/guava/28.1-jre/guava-28.1-jre.jar
public long getFolderSizeViaGuava() {
File folder = new File("src/test/resources");
Iterable<File> files = Files.fileTreeTraverser()
.breadthFirstTraversal(folder);
long size = StreamSupport.stream(files.spliterator(), false)
.filter(f -> f.isFile())
.mapToLong(File::length).sum();
return size;
}
To get file size,
File file = new File("PATH TO YOUR FILE");
long s = file.length();
System.out.println(s);
answered Nov 11, 2019 at 1:52
Du-LacosteDu-Lacoste
11.3k2 gold badges67 silver badges50 bronze badges
fun getSize(context: Context, uri: Uri?): Float? {
var fileSize: String? = null
val cursor: Cursor? = context.contentResolver
.query(uri!!, null, null, null, null, null)
try {
if (cursor != null && cursor.moveToFirst()) {
// get file size
val sizeIndex: Int = cursor.getColumnIndex(OpenableColumns.SIZE)
if (!cursor.isNull(sizeIndex)) {
fileSize = cursor.getString(sizeIndex)
}
}
} finally {
cursor?.close()
}
return fileSize!!.toFloat() / (1024 * 1024)
}
answered Dec 23, 2021 at 12:45
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
The length() function is a part of File class in Java . This function returns the length of the file denoted by the this abstract pathname was length.The function returns long value which represents the number of bytes else returns 0L if the file does not exists or if an exception occurs.
Function signature:
public long length()
Syntax:
long var = file.length();
Parameters: This method does not accept any parameter.
Return Type The function returns long data type that represents the length of the file in bits.
Exception: This method throws Security Exception if the write access to the file is denied Below programs illustrate the use of the length() function:
Example 1: The file “F:\program.txt” is an existing file in F: Directory.
Java
import
java.io.*;
public
class
solution {
public
static
void
main(String args[])
{
File f =
new
File(
"F:\program.txt"
);
System.out.println(
"length: "
+ f.length());
}
}
Output:
length: 100000
Example 2: The file “F:\program1.txt” is empty
Java
import
java.io.*;
public
class
solution {
public
static
void
main(String args[])
{
File f =
new
File(
"F:\program.txt"
);
System.out.println(
"length: "
+ f.length());
}
}
Output:
length: 0
Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file.
Last Updated :
09 Oct, 2022
Like Article
Save Article
Overview
The Java programming language includes a lot of APIs that help developers to do more efficient coding. One of them is Java IO API which is designed to read and write data (input and output). For example, read data from a file or over the network and then write a response back over the network.
Scope
- This article explains Java IO streams in brief and the different ways to get file size, along with java programs.
- We also learn about various classes such as File, FileChannel, and FileUtils.
Introduction to Java IO Streams
The Java IO API is found in the java.io package. The Java IO package focuses mainly on input and output to files, network streams, internal memory buffers, etc. On the other hand, it lacks classes for opening network sockets, which are required for network communication. We need to use the Java Networking API for this purpose.
The Java IO package provides classes that include methods that are used to obtain metadata of a file. The definition of metadata is «data about other data». With a file system, the data is contained in its files and directories, and the metadata tracks information about each of these objects. In this tutorial, we are going to learn about various ways to determine the size of a file in Java.
File size is a measure of how much data it contains or how much storage it usually takes. The size of a file is usually measured in bytes. In Java, the following classes will help us to 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
Takeaway:
- To speed up I/O operations, Java uses the concept of a stream.
- All classes required for input and output operations are included in the java.io package except the one for opening network sockets.
Java Getting File Size Using File Class
The Java File class is an abstract representation of file and directory pathnames. It is found in the java. io package. This class contains various methods which can be used to manipulate the files like creating new files and directories, searching and deleting files, enlisting the contents of a directory, as well as determining the attributes of files and directories. This is the oldest API to find out the size of a file in Java.
The File class in java contains a length() method that returns the size of the file in bytes. To use this method, we first need to create an object of the File class by calling the File(String pathname) constructor. This constructor creates a new File instance by converting the given pathname string into an abstract pathname.
An abstract pathname consists of an optional prefix string, such as disk drive specifiers, “/” for Unix, or “” for Windows, and a sequence of zero or more string names.
The prefix string is platform-dependent. The last name in the abstract pathname represents a file or directory. All other names represent directories.
For example, «c:datainputfile.txt»
File file = new File("c:\data\inputfile.txt"); //pass the pathname as an argument
Now we can apply the File class length() method to the File object. It will return the length, in bytes, of the file denoted by this abstract pathname, or 0L if the file does not exist. The return value is unspecified if this pathname denotes a directory. So, we need to make sure the file exists and isn’t a directory before invoking this java method to determine file size.
Here is the input file:
A simple java program to determine file size using the File class is shown below:
import java.io.File; class javaFileClassExample { public static void printFileSize(File file) { //check if the file exists or not if (file.exists()) { // size of a file (in bytes) long bytes = file.length(); // print the file size System.out.println(bytes + " bytes"); System.out.println(bytes / 1024.0 + " kb"); } else { // if the file doesn't exist System.out.println("File does not exist!"); } } public static void main(String args[]) { String pathName = "C:\Users\SC\Desktop\file.txt"; // Create the File instance with pathName File file = new File(pathName); printFileSize(file); } }
Output:
Explanation: Since the file exists, it will return the file size in bytes, else it would have return the “File does not exist!” statement.
Takeaway:
- If the pathname argument is null in File(String pathname), it will throw NullPointerException.
- Even if the file does not exist, it won’t throw an exception, it will return 0L.
Get File Size In Java Using FileChannel Class
The Java FileChannel class is a channel that is connected to a file by which we can read data from a file and write data to a file or access file metadata. It is found in java.nio package (NIO stands for non-blocking I/O) which is a collection of Java programming language APIs that offer features for intensive I/O operations.
File channels are safe for use by multiple concurrent threads, making Java NIO more efficient than Java IO. However, only one operation that involves updating a channel’s position or changing its file size is allowed at a time. If other threads are performing a similar operation, it will block them until the previous operation is completed.
Note: Although FileChannel is a part of the java.nio package, its operations cannot be set into non-blocking mode, it always runs in blocking mode.
Also, we can’t create objects of the FileChannel class directly, we need to create them by invoking the open() method defined by this class. This method opens or creates a file, returning a file channel to access the file. After creating a FileChannel instance we can call the size() method which will return the current size of this channel’s file, measured in bytes.
Here is the input file we need to parse −
Hello World in Java!
A simple java program to determine file size using the FileChannel class is shown below.
import java.io.File; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.Paths; class javaFileChannelClassExample { public static void printFileSize(String fileName) { // converts the path string to a path Path filePath = Paths.get(fileName); // declaring an object of FileChannel type FileChannel fileChannel; try { // pass the path to open the file fileChannel = FileChannel.open(filePath); // print the file size (in bytes) long fileSize = fileChannel.size(); System.out.println("Size of the file is " + fileSize + " bytes"); // close the channel fileChannel.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String args[]) { // path of the file in string format String fileName = "C:\Users\SC\Desktop\file.txt"; printFileSize(fileName); } }
Output:
Size of the file is 20 bytes
Explanation: Since the file exists, it will return the file size in bytes, else it would have thrown the java.nio.file.NoSuchFileException error.
Takeaway:
- We can’t create objects of FileChannel class directly, we have to create it by invoking the open() method.
- FileChannel is thread-safe but allows only one operation at a time that involves the channel’s position or changing its file’s size, blocking other similar operations.
Java Getting File Size Using Apache Commons IO FileUtils Class
The Java FileUtils are general file manipulation utilities. This class is found in the org.apache.commons.io package. It includes methods to perform various operations like writing to a file, reading from a file, making directories, copying and deleting files and directories, etc.
The Java FileUtils class provides the sizeOf() method that returns the size of the file in bytes. Firstly, we need to create a File instance and then pass it to the sizeOf() method.
It will return the size of the specified file or directory. If the provided File is a regular file, then the file’s length is returned. If the argument is a directory, then the size of the directory is calculated recursively.
Note that overflow is not detected, and the return value may be negative if overflow occurs. We can use sizeOfAsBigInteger(File) for an alternative method that does not overflow.
Here is the input file we need to parse −
Hello World in Java!
A simple java program to determine file size using the FileUtils class is shown below.
import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class javaFileUtilsClassExample { public static void printFileSize(String fileName) { // try - catch block if exception occurs try { // creates a File instance with fileName File file = new File(fileName); // print the file size (in bytes) long fileSize = FileUtils.sizeOf(file); System.out.println("Size of the file is " + fileSize + " bytes"); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { // path of the file in string format String fileName = "C:\Users\SC\Desktop\file.txt"; printFileSize(fileName); } }
Output:
Size of the file is 20 bytes
Explanation: Since the file exists, it returns the file size in bytes, else it would have thrown an exception.
Takeaway:
- The sizeOf() method will return the size of the specified file in bytes.
- If the file is null, it will throw NullPointerException, and if the file does not exist, it will throw IllegalArgumentException,
Conclusion
- The java.io package provides for system input and output through data streams, serialization, and the file system.
- Java provides various classes to determine the file size i.e. File, FileChannel, and FileUtils class.
- The File class is found in the java.io package and provides a length() method to get file size.
- The FileChannel class is found in the java.nio package and provides size() method to determine the file size.
- FileChannel is thread-safe, making Java NIO more efficient than Java IO.
- The operations of FileChannel are blocking and can’t be set into non-blocking mode.
- The Java FileUtils class is found in org.apache.commons.io package and provides sizeOf() method to determine the file size.
Сегодня мы узнаем способ получить размер файла в Java. Как всегда, сначала опишем что, как и почему в теории, а затем на практике закрепим знания.
Как узнать размер файла. Теория
Метод java.io.File length()
может быть использован для получения размера файла. Этот метод возвращает размер файла в байтах.
При использовании метода length()
вы всегда должны проверить файл — существует он или нет. Если файл не существует, этот метод возвращает ноль.
Как узнать размер файла в Java. Практика
Вот пример простой программы, которая вычисляет размер файла на Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package ua.com.prologistic; import java.io.File; // в этом классе мы получаем размер файла public class FileSize { public static void main(String[] args) { File file = new File(«/Users/prologistic/Desktop/TestVideo.mov»); if(file.exists()){ System.out.println(getFileSizeBytes(file)); System.out.println(getFileSizeKiloBytes(file)); System.out.println(getFileSizeMegaBytes(file)); }else System.out.println(«Файла нет!»); } // метод возвращает размер файла в мегабайтах // длину файла делим на 1 мегабайт (1024 * 1024 байт) и узнаем количество мегабайт private static String getFileSizeMegaBytes(File file) { return (double) file.length()/(1024*1024)+» mb»; } // метод возвращает размер файла в килобайтах // длину файла делим на 1 килобайт (1024 байт) и узнаем количество килобайт private static String getFileSizeKiloBytes(File file) { return (double) file.length()/1024 + » kb»; } // просто вызываем метод length() и получаем размер файла в байтах private static String getFileSizeBytes(File file) { return file.length() + » bytes»; } } |
А вот и результат выполнения программы:
183386967 bytes 185885.7099609375 kb 182.46651363372803 mb |
В этом посте будет обсуждаться, как получить размер файла в байтах в Java.
1. Использование File#length()
метод
Простое решение — вызвать File#length()
метод, который возвращает размер файла в байтах. Чтобы получить размер файла в МБ, вы можете разделить длину (в байтах) на 1024 * 1024
. Обратите внимание, что File#length()
метод возвращает длину 0, если файл является каталогом или произошло исключение ввода-вывода.
import java.io.File; public class Main { public static void main(String[] args) { File file = new File(«/var/system.logs»); long size = file.length(); System.out.println(«The file size is « + size + » bytes»); } } |
Скачать код
2. Использование Files.size()
метод
Java НИО Класс файлов предоставляет несколько служебных методов для операций с файлами. Чтобы получить размер файла в байтах, вы можете использовать Files.size()
метод. Обратите внимание, что фактический размер файла может отличаться из-за сжатия, поддержки разреженных файлов или по другим причинам.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class Main { public static void main(String[] args) { String filePath = «/var/system.logs»; try { long size = Files.size(Path.of(filePath)); System.out.println(«The file size is « + size + » bytes»); } catch (IOException e) { e.printStackTrace(); } } } |
Скачать код
3. Использование FileChannel#size()
метод
Другой вариант — получить входной поток файла для файла в файловой системе и получить связанный файловый канал. Затем вы можете использовать size()
метод, который возвращает текущий размер файла канала, измеренный в байтах.
import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class Main { public static void main(String[] args) { String filePath = «/var/system.logs»; try (FileInputStream fis = new FileInputStream(new File(filePath))) { long size = fis.getChannel().size(); System.out.println(«The file size is « + size + » bytes»); } catch (IOException e) { e.printStackTrace(); } } } |
Скачать код
Это все, что касается получения размера файла в байтах в Java.
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования