Java example file size

How to get a files size in bytes using Java

This example shows how to get a file’s size in bytes by using file.exists() and file.length() method of File class.

import java.io.File; public class Main < public static long getFileSize(String filename) < File file = new File(filename); if (!file.exists() || !file.isFile()) < System.out.println("File doesn\'t exist"); return -1; >return file.length(); > public static void main(String[] args) < long size = getFileSize("c:/java.txt"); System.out.println("Filesize in bytes: " + size); >>

Result

The above code sample will produce the following result.To test this example, first create a text file ‘java.txt’ in ‘C’ drive.The size may vary depending upon the size of the file.

The following is another sample example of files size in java

import java.io.File; public class FileSizeExample < public static void main(String[] args) < File file = new File("C:\\Users\\TutorialsPoint7\\Desktop\\abc.png"); if(file.exists()) < double bytes = file.length(); double kilobytes = (bytes / 1024); double megabytes = (kilobytes / 1024); double gigabytes = (megabytes / 1024); double terabytes = (gigabytes / 1024); double petabytes = (terabytes / 1024); double exabytes = (petabytes / 1024); double zettabytes = (exabytes / 1024); double yottabytes = (zettabytes / 1024); System.out.println("bytes : " + bytes); System.out.println("kilobytes : " + kilobytes); System.out.println("megabytes : " + megabytes); System.out.println("gigabytes : " + gigabytes); System.out.println("terabytes : " + terabytes); System.out.println("petabytes : " + petabytes); System.out.println("exabytes : " + exabytes); System.out.println("zettabytes : " + zettabytes); System.out.println("yottabytes : " + yottabytes); >else < System.out.println("File does not exists!"); >> >

The above code sample will produce the following result.To test this example, first create a text file ‘java.txt’ in ‘C’ drive.The size may vary depending upon the size of the file.

bytes : 6119.0 kilobytes : 5.9755859375 megabytes : 0.005835533142089844 gigabytes : 5.698762834072113E-6 terabytes : 5.565198080148548E-9 petabytes : 5.434763750145066E-12 exabytes : 5.307386474751041E-15 zettabytes : 5.182994604249064E-18 yottabytes : 5.061518168211976E-21

Источник

Java get file size

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

  1. Java get file size using File class
  2. Get file size in java using FileChannel class
  3. Java get file size using Apache Commons IO FileUtils class

java file size, java get file size

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"; >> 

java get file size

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.

Читайте также:  Python telegram bot api inlinekeyboardmarkup

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.

Источник

Getting File Information Using Java IO streams

Java Course - Mastering the Fundamentals

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.

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
  • 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:\data\inputfile.txt»

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.

Читайте также:  Python lambda return function

input file

Here is the input file:

A simple java program to determine file size using the File class is shown below:

Explanation: Since the file exists, it will return the file size in bytes, else it would have return the “File does not exist!” statement.

  • 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 −

A simple java program to determine file size using the FileChannel class is shown below.

Explanation: Since the file exists, it will return the file size in bytes, else it would have thrown the java.nio.file.NoSuchFileException error.

  • 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 −

A simple java program to determine file size using the FileUtils class is shown below.

Explanation: Since the file exists, it returns the file size in bytes, else it would have thrown an exception.

  • 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.
Читайте также:  Javascript строка несколько строк

Источник

Java file size

In this article we show several ways how to determine the size of a file in Java.

is a measure of how much data a computer file contains or, alternately, how much storage it consumes. The file size is usually expressed in bytes.

In Java, we can determine the size of a file with File , FileChannel , Files , and Apache Commons’ FileUtils . A a rule of thumb, in new code we should use the Files class.

green, chair, pen, computer, apple, book, scissors

In our examples, we are going to use the words.txt file located in src/main/resources directory.

Java file size with File

The length method of File returns the file size. This is the oldest API to find out the size of a file in Java.

package com.zetcode; import java.io.File; public class JavaFileSizeEx < public static void main(String[] args) < String fileName = "src/main/resources/words.txt"; File f = new File(fileName); long fileSize = f.length(); System.out.format("The size of the file: %d bytes", fileSize); >>

The code example determines the file size using File’s length method.

Java file size with FileChannel

FileChannel has the size method to determine the size of the file.

package com.zetcode; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.Paths; public class JavaFileSizeEx2 < public static void main(String[] args) throws IOException < String fileName = "src/main/resources/words.txt"; Path filePath = Paths.get(fileName); FileChannel fileChannel = FileChannel.open(filePath); long fileSize = fileChannel.size(); System.out.format("The size of the file: %d bytes", fileSize); >>

The code example determines the file size using FileChannel’s size method.

Java file size with Files

Files has the size method to determine the size of the file. This is the most recent API and it is recommended for new Java applications.

package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class JavaFileSizeEx3 < public static void main(String[] args) throws IOException < String fileName = "src/main/resources/words.txt"; Path filePath = Paths.get(fileName); long fileSize = Files.size(filePath); System.out.format("The size of the file: %d bytes", fileSize); >>

The code example determines the file size using Files’ size method.

Java file size with FileUtils

In the last example, we determine the file size with Apache Commons’ FileUtils . Its method for finding out the file size is sizeOf .

For this example, we need the commons-io dependency.

package com.zetcode; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class JavaFileSizeEx4 < public static void main(String[] args) throws IOException < String fileName = "src/main/resources/words.txt"; File f = new File(fileName); long fileSize = FileUtils.sizeOf(f); System.out.format("The size of the file: %d bytes", fileSize); >>

The code example determines the file size using Apache Commons’ FileUtils’ sizeOf method.

In this article we have shown how to determine the size of a file in Java.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

Оцените статью