This is a REALLY old thread, but it was still the first thing to pop up when I googled the issue. So I just wanted to add this:

InputStream inputStream = conn.getInputStream();
int length = inputStream.available();

Worked for me. And MUCH simpler than the other answers here.

Warning This solution does not provide reliable results regarding the total size of a stream. Except from the JavaDoc:

Note that while some implementations of {@code InputStream} will return * the total number of bytes in the stream, many will not.

Answer from W. B. Reed on Stack Overflow
🌐
GitHub
gist.github.com › mikeblum › ebb976fb396af70f372c642de22656ba
Calculate the size of an InputStream · GitHub
Calculate the size of an InputStream · Raw · sizeChecker.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Discussions

java - How to get the size of an InputStream? - Stack Overflow
I'm having an InputStream from a ProcessBuilder that acutally reads the stdout stream. Question: how can I know the size of that inmemory InputStream, so I can write it to a HttpResponse http head... More on stackoverflow.com
🌐 stackoverflow.com
February 19, 2016
java - Get total size of file in bytes - Stack Overflow
Possible Duplicate: java get file size efficiently More on stackoverflow.com
🌐 stackoverflow.com
Java InputStream size - Stack Overflow
I need to get the size in bytes of an InputStream without creating a File instance. Is there any way to do it using Java NIO? More on stackoverflow.com
🌐 stackoverflow.com
get size of InputStream in Java - Stack Overflow
@bereal : no because it will give me size of stream(file) before encryption ... You have to read the whole stream for that. Streams are probably not even complete when you start reading from them, so the size may not be known at that time. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Java2s
java2s.com › example › java-utility-method › file-size-get › getfilesize-inputstream-inputstream-4a1e3.html
Java File Size Get getFileSize(InputStream inputStream)
get File Size · Open Source License · public static final int getFileSize(InputStream inputStream) //package com.java2s; //License from project: Open Source License import java.io.IOException; import java.io.InputStream; public class Main { public static final int getFileSize(InputStream ...
🌐
Coderanch
coderanch.com › t › 380759 › java › Size-InputStream
Size of an InputStream (Java in General forum at Coderanch)
If you want an exact figure, you could try wrapping the ServletOutputStream you hook the ObjectOutputStream to and measure the bytes being written. You could also observe the network traffic with a sniffer, but I have no experience with that. ... A general idea: if you want to see how may bytes ...
🌐
CodingTechRoom
codingtechroom.com › question › determine-inputstream-size-java
How to Determine the Size of an InputStream in Java? - CodingTechRoom
InputStream uploadedStream = null; ... of the InputStream here } } To determine the size of an InputStream in Java, you can use the available() method provided by the InputStream class....
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › java io › file size in java
File Size in Java | Baeldung
November 29, 2023 - 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.
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - The Tabnine Code Library is no longer available — but you can still get the answers and suggestions you need from our AI code assistant.
Top answer
1 of 2
1

There's no way to do this reliably across all FTP services.

The FTP protocol does not provide a way to get file sizes, so you would need to resort to requesting a directory listing and unpicking the (server specific) text that you get back. Furthermore, there is no guarantee that directory listing will be enabled, or that you will have permission to list the directory.

Having said this, some FTP libraries can be configured to attempt to get a file size. For example, with the Apache FTPClient library you can (try to) use the listFiles(String) method and look at the resulting FTPFile object.

EDIT

@Kevin Brock mentions the FTP SIZE command as a possibility.

  • This is command was first defined in RFC 3659 in 2007. A lot of deployed FTP server software is much older than that.
  • SIZE is an optional command; i.e. even RFC 3659 compliant servers are not required to support it.
  • Even if SIZE is supported by a server, the current Apache FTPClient APIs do not include a method for getting the size of a file (apart from via listFiles). Of course, this may change in the future.
  • The ftp4j FTPClient class apparently does implement SIZE and make it available via its fileSize(...) method.
2 of 2
0

I haven't found a simple command to do this either. My solution was to call the skip command, which should return the number of bytes skipped. Sum this until skip returns 0. There is a possibility that skip can return 0 for reasons other than end of file, but in the field it seems to work well.

Here is some example code:

InputStream checkStream = m_ftpClient.retrieveFileStream(name);

long fileLength = 0;
long transferredLength = 0;
do
{
    transferredLength = checkStream.skip(MAX_BYTES);
    fileLength += transferredLength;
}while(transferredLength > 0);
🌐
Coderanch
coderanch.com › t › 588624 › java › size-InputStream
Get size of InputStream [Solved] (I/O and Streams forum at Coderanch)
July 31, 2012 - Is there any way to do this using the Java NIO package? Thanks in advance! ... Welcome to the Ranch! It's not possible to get the size of any arbitrary InputStream, because often not all data is available yet. For instance, if you read data from a Socket, some data may not even have been sent yet.
🌐
Scaler
scaler.com › home › topics › java › getting file information using java io streams
How to get Java File Size - Scaler Topics
April 8, 2024 - This article explains Java IO streams in brief & different ways to get java file size, along with java programs & various classes such as File, FileChannel, and FileUtils.
🌐
Coderanch
coderanch.com › t › 526580 › java › size-stream
Getting the size of a stream (I/O and Streams forum at Coderanch)
February 8, 2011 - But now i want to add a second value over the original slider which represents how many bytes have been downloaded into the buffer for playback. m_audioInputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(SomeUrlsInputStream)); i tried to add another thread which reads from m_audioInputStream until -1 is returned but that leads to strange effects in the playback. Do i have to create another BufferedInputStream? Is the file then downloaded twice?
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-io-fileinputstream-class-java
Java FileInputStream Class - GeeksforGeeks
November 3, 2025 - public class FileInputStream extends InputStream · Example: FileInputStream class to read data from file. Java · import java.io.*; public class Geeks{ public static void main(String[] args){ // Use try-with-resources to automatically close the // stream try (FileInputStream fi = new FileInputStream("file1.txt")) { // Display file channel information System.out.println("Channel: " + fi.getChannel()); // Display file descriptor System.out.println("File Descriptor: " + fi.getFD()); // Show available bytes in the stream System.out.println("Number of remaining bytes: " + fi.available()); // Skip
🌐
Reddit
reddit.com › r/javahelp › at what length does reading from an inputstream break down when using a buffer?
r/javahelp on Reddit: At what length does reading from an InputStream break down when using a buffer?
January 18, 2023 -

A while ago I was reading data from a file, which included a bunch of modules, consisting of a header and a payload. When reading the payloads, I initially had something like this code:

byte[] buffer = new byte[size]; // Size of the payload was from the header
int read = stream.read(buffer); // stream is the InputStream being read
if (read != size) {
    // Throw error here
}

This ended up having some problems, and as I was using a Java version past Java 9, I just used the readNBytes method.

byte[] bytes = stream.readNBytes(size);

This solved the issues I was having, but brought the question to me, why does this happen? Why does reading to a buffer stop reading accurately if the size of the buffer is very large?

I'm currently writing a program where I am reading a file and performance is relevant, so I would rather use buffering, rather than readNBytes, but at what length does reading with a byte buffer begin to have problems?

Top answer
1 of 4
2
There is no inaccuracy or problems. Streams don't always immediately have the number of bytes you request, as the idea of a stream is that the data is going by like things floating down a stream rather than being all in one place. For example, files load very slowly from disk, and if you're using an InputStream, it will load a portion at a time rather than having the entire file in memory ready to copy into your buffer. Storing the file's data in memory is your job with the read calls that fill your buffer as the file data comes in. Since it's sometimes useful to process partial data, read is designed to give what data it has now (at least until your buffer fills up) so that you can begin processing it rather than having to wait for all the data to be loaded. Note that the documentation says: Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached. You should have either processed the partial data as it came in or kept reading until you received either the number of bytes you needed or the -1 that indicates the end of the stream if you were waiting for that. In the second case: int i = 0; int bytesReceivedThisRead; while ((bytesReceivedThisRead = stream.read(buffer, i, buffer.length - i)) > 0) { i += bytesReceivedThisRead; } if (bytesReceivedThisRead == -1) { // Handle the stream ending before the buffer is filled } else { // Handle the buffer being filled up } In the third case: int i = 0; int bytesReceivedThisRead; while ((bytesReceivedThisRead = stream.read(buffer, i, buffer.length - i)) != -1) { if (bytesReceivedThisRead == 0) { // Handle the buffer being full before all data is read } i += bytesReceivedThisRead; } // Handle the buffer being filled with `i` bytes just as the stream ends
2 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.