Java file get file length

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

Hot Network Questions

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

Читайте также:  Php ооп this self

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

File Size in Java

announcement - icon

Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.

Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.

The feedback is available from the minute you are writing it.

Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.

Of course, Digma is free for developers.

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we’ll learn how to get the size of a file in Java – using Java 7, the new Java 8 and Apache Common IO.

Finally – we will also get a human readable representation of the file size.

2. Standard Java IO

Let’s start with a simple example of calculating the size of a file – using the File.length() method:

private long getFileSize(File file)

We can test our implementation relatively simply:

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

Note that, by default, the file sizes is calculated in bytes.

3. With Java NIO

Next – let’s see how to use the NIO library to get the size of the file.

In the following example, we’ll use the FileChannel.size() API to get the size of a file in bytes:

@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. With Apache Commons IO

Next – let’s see how to get the file size using Apache Commons IO. In the following example – we simply use FileUtils.sizeOf() to get the file size:

@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); >

Note that, for security restricted files, FileUtils.sizeOf() will report the size as zero.

5. Human Readable Size

Finally – let’s see how to get a more user readable representation of the file size using Apache Commons IO – not just a size in bytes:

@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. Conclusion

In this tutorial, we illustrated examples of using Java and Apache Commons IO to calculate the size of a file in the file system.

The implementation of these examples can be found in the GitHub project – this is a Maven-based project, so it should be easy to import and run as it is.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

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" 

Источник

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.

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.

Источник

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