Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Example – Getting File Size

Java Example - Getting File Size

Java Examples Java Examples

The following example demonstrates how to use the File class's file.exists() and file.length() methods to get the file size in bytes (1KB = 1024 bytes):

Main.java File

import

java

.

io

.

File

;

public

class

Main

{

public

static

long

getFileSize

(

String

filename

)

{

File

file

=

new

File

(

filename

)

;

if

(

!

file

.

exists

(

)

|| !

file

.

isFile

(

)

)

{

System

.

out

.

println

(

"

File does not exist

"

)

;

return

1

;

}

return

file

.

length

(

)

;

}

public

static

void

main

(

String

[

]

args

)

{

long

size

=

getFileSize

(

"

c:/java.txt

"

)

;

System

.

out

.

println

(

"

The size of java.txt is:

"

size

)

;

}

}

The output of the above code is (the java.txt file is on the C: drive):



java.txt文件大小为: 480

Java Examples Java Examples