Trong Java, chúng ta có thể xác định kích thước của file trên ổ đĩa với File, FileChannel , Files và FileUtils. Quy tắc thumb, chúng ta nên sử dụng class Files trong source code mới.
Ví dụ: chúng ta có file sample.txt với nội dung như sau:
one, two, three, four, five, six, seven, eight, nine, ten
Sử dụng File
Phương thức length() của class File trả về kích thước của file. Đây là API đầu tiên trong Java được sử dụng để xác định kích thước file.
FileSizeEx1.java
package net.vncoding; import java.io.File; public class FileSizeEx1 { public static void main(String[] args) { String fileName = "src/sample.txt"; File f = new File(fileName); long fileSize = f.length(); System.out.format("The size of the file: %d bytes", fileSize); } }
Kết quả:
The size of the file: 57 bytes
Sử dụng FileChannel
Class FileChannel có phương thức size() để xác định kích thước của file.
FileSizeEx2.java
package net.vncoding; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.Paths; public class FileSizeEx2 { public static void main(String[] args) throws IOException { String fileName = "src/sample.txt"; Path filePath = Paths.get(fileName); FileChannel fileChannel = FileChannel.open(filePath); long fileSize = fileChannel.size(); System.out.format("The size of the file: %d bytes", fileSize); } }
Kết quả:
The size of the file: 57 bytes
Sử dụng Files
Files có phương thức size() xác định kích thước của file. Đây là API mới được public và đươc khuyên dùng trong việc phát triển Java application.
FileSizeEx3.java
package net.vncoding; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileSizeEx3 { public static void main(String[] args) throws IOException { String fileName = "src/sample.txt"; Path filePath = Paths.get(fileName); long fileSize = Files.size(filePath); System.out.format("The size of the file: %d bytes", fileSize); } }
Kết quả:
The size of the file: 57 bytes
Sử dụng FileUtils
Trong ví dụ cuối, chúng ta xác định kích thước file với FileUtils của Apache common.
FileSizeEx3.java
package net.vncoding; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class FileSizeEx4 { public static void main(String[] args) throws IOException { String fileName = "src/sample.txt"; File f = new File(fileName); long fileSize = FileUtils.sizeOf(f); System.out.format("The size of the file: %d bytes", fileSize); } }
Giải thích:
Để sử dụng được FileUtils của Apache common, chúng ta cần download package org.apache.commons.io. Sau đó giải nén và add external Java file như hình dưới đây.
Kết quả:
The size of the file: 57 bytes
Leave a Reply
You must be logged in to post a comment.