Java получить размер файла

Размер файла в Java

В этом кратком руководстве мы узнаем, как получитьsize of a file in Java — с использованием Java 7, новой Java 8 и Apache Common IO.

Наконец, мы также получим удобочитаемое представление размера файла.

2. Стандартный Java IO

Начнем с простого примера расчета размера файла с помощью методаFile.length():

private long getFileSize(File file)

Мы можем проверить нашу реализацию относительно просто:

@Test public void whenGetFileSize_thenCorrect() < long expectedSize = 12607; File imageFile = new File("src/test/resources/image.jpg"); long size = getFileSize(imageFile); assertEquals(expectedSize, size); >

Обратите внимание, что по умолчанию размеры файлов рассчитываются в байтах.

3. С Java NIO

Далее — давайте посмотрим, как использовать библиотеку NIO, чтобы получить размер файла.

В следующем примере мы воспользуемся APIFileChannel.size(), чтобы получить размер файла в байтах:

@Test public void whenGetFileSizeUsingNioApi_thenCorrect() throws IOException < long expectedSize = 12607; Path imageFilePath = Paths.get("src/test/resources/image.jpg"); FileChannel imageFileChannel = FileChannel.open(imageFilePath); long imageFileSize = imageFileChannel.size(); assertEquals(expectedSize, imageFileSize); >

4. С Apache Commons IO

Далее — давайте посмотрим, как получить размер файла с помощьюApache Commons IO. В следующем примере мы просто используемFileUtils.sizeOf() для получения размера файла:

@Test public void whenGetFileSizeUsingApacheCommonsIO_thenCorrect() < long expectedSize = 12607; File imageFile = new File("src/test/resources/image.jpg"); long size = FileUtils.sizeOf(imageFile); assertEquals(expectedSize, size); >

Обратите внимание, что для файлов с ограничениями безопасностиFileUtils.sizeOf() сообщит о размере нулевого размера.

5. Удобочитаемый размер

Наконец, давайте посмотрим, как получить более удобочитаемое представление размера файла с помощьюApache Commons IO, а не только размер в байтах:

@Test public void whenGetReadableFileSize_thenCorrect() < File imageFile = new File("src/test/resources/image.jpg"); long size = getFileSize(imageFile); assertEquals("12 KB", FileUtils.byteCountToDisplaySize(size)); >

6. Заключение

В этом руководстве мы проиллюстрировали примеры использования Java и Apache Commons IO для вычисления размера файла в файловой системе.

Реализацию этих примеров можно найти вthe GitHub project — это проект на основе Maven, поэтому его должно быть легко импортировать и запускать как есть.

Источник

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.

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.

Источник

Java получить размер файла

Java getfilesize, размер файла java, получить размер файла в java, метод длины файла java, размер канала файла, размер файла, размер файла байт, мегабайт, ГБ.

Сегодня мы рассмотрим различные способы определения размера файла в Java.

Java получить размер файла

Существуют различные классы, которые мы можем использовать для программы java get file size. Некоторые из них являются;

  1. Java получает размер файла с помощью Файла класса
  2. Получить размер файла в java с помощью FileChannel class
  3. Java получает размер файла с помощью Apache Commons IO Файлы класс

Прежде чем мы рассмотрим пример программы для определения размера файла, у нас есть образец pdf-файла размером 2969575 байт.

Java получает размер файла с помощью класса файла

Метод Java File length() возвращает размер файла в байтах. Возвращаемое значение не указано, если этот файл обозначает каталог. Поэтому, прежде чем вызывать этот метод для определения размера файла в java, убедитесь, что файл существует, а не является каталогом.

Ниже приведен простой пример программы java для получения размера файла с использованием класса File.

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 с помощью класса FileChannel

Мы можем использовать метод FileChannel size() для получения размера файла в байтах.

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 получает размер файла с помощью класса FileUtils ввода-вывода Apache Commons

Если вы уже используете Apache Commons IO в своем проекте, вы можете использовать метод FileUtils sizeOf для получения размера файла на 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"); >>

Это все для программ java get с размером файла.

Читайте ещё по теме:

Источник

Читайте также:  Css link not underlined
Оцените статью