- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to get the file size from the server in Java
Problem Description
How to get the file size from the server?
Solution
Following example demonstrates How to get the file size from the server.
import java.net.URL; import java.net.URLConnection; public class Main { public static void main(String[] argv) throws Exception { int size; URL url = new URL("http://www.server.com"); URLConnection conn = url.openConnection(); size = conn.getContentLength(); if (size < 0) System.out.println("Could not determine file size."); else System.out.println("The size of file is = " + size + "bytes"); conn.getInputStream().close(); } }
Result
The above code sample will produce the following result.
The size of file is = 1312bytes
The following is an another example to get the file size from the server.
import java.net.URL; import java.net.URLConnection; public class NewClass { public static void main(String[] argv) throws Exception { int size; URL url = new URL("https://www.tutorialspoint.com/javaexamples/net_multisoc.htm"); URLConnection conn = url.openConnection(); size = conn.getContentLength(); if (size < 0) System.out.println("file size is empty."); else System.out.println("File size is = " + size + "bytes"); conn.getInputStream().close(); } }
The above code sample will produce the following result.
File size is = 18862bytes
java_networking.htm
Advertisements