Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
78 views
in JAVA by (178k points)
How can I get the size of a file in Java?

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

In Java, you can get the size of a file using the length() method of the File class. 

Here's an example of how to get the size of a file in Java:

import java.io.File;

public class GetFileSizeExample {
    public static void main(String[] args) {
        String fileName = "example.txt";
        File file = new File(fileName);
        if (file.exists()) {
            long fileSize = file.length();
            System.out.println("File size in bytes: " + fileSize);
        } else {
            System.out.println("File does not exist.");
        }
    }
}
 

In this example, we create a new File object representing the file we want to get the size of, using the filename "example.txt". We then call the exists() method on the File object to check if the file exists. If the file exists, we call the length() method on the File object, which returns the size of the file in bytes.

We then print the size of the file to the console. If the file does not exist, we print a message indicating that the file does not exist.

It's important to note that when getting the size of a file in Java, the size is returned in bytes. If you want to convert the size to another unit, such as kilobytes or megabytes, you can divide the size by the appropriate factor. For example, to get the size of the file in kilobytes, you can divide the size by 1024.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Apr 27, 2023 in JAVA by kvdevika (178k points)
0 votes
1 answer
asked Apr 27, 2023 in JAVA by kvdevika (178k points)
0 votes
1 answer
asked Apr 27, 2023 in JAVA by kvdevika (178k points)
0 votes
1 answer
asked Apr 27, 2023 in JAVA by kvdevika (178k points)

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...