我如何获得文件长度?

时间:2014-11-02 13:07:43

标签: java file

我试图获取文件的长度(以字节为单位),但每次测试不同的文件时,结果总是为4065123.0。

这是我的代码的相关部分:

File file = new File(path + filename);
if(!file.exists()) {
    System.out.println("File does not exist");
} else {
    double bytes = file.length();
}

如何正确获取文件的长度?

4 个答案:

答案 0 :(得分:1)

尝试:

    File file =new File("myfile_in_test.java");

    if(file.exists()){

        final double bytes = file.length();
        final double kilobytes = (bytes / 1024);

        System.out.println("bytes : " + bytes);
        System.out.println("kilobytes : " + kilobytes);
    }else{
         System.out.println("File does not exists!");
    }

答案 1 :(得分:0)

这是一个显示它工作得很好的例子。

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        File file = File.createTempFile("deleteme", ".txt");
        file.deleteOnExit();
        Thread main = Thread.currentThread();
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    do {
                        Thread.sleep(200);
                        long length = file.length();
                        System.out.println("File " + file + " is " + length + " bytes long.");
                    } while(main.isAlive());
                    System.out.println("Finished");
                } catch (InterruptedException e) {
                    System.err.println("Interrupted");
                }
            }
        }, "monitor");
        t.start();

        FileOutputStream fos = new FileOutputStream(file);
        for(int i=0;i<2000;i++) {
            fos.write("words words words words words words words words words words words\n".getBytes());
            Thread.sleep(1);
        }
        fos.close();
    }
}

打印类似的东西。

File /tmp/deleteme4214599935706768614.txt is 11880 bytes long.
File /tmp/deleteme4214599935706768614.txt is 23562 bytes long.
File /tmp/deleteme4214599935706768614.txt is 35376 bytes long.
File /tmp/deleteme4214599935706768614.txt is 47256 bytes long.
File /tmp/deleteme4214599935706768614.txt is 59136 bytes long.
File /tmp/deleteme4214599935706768614.txt is 70950 bytes long.
File /tmp/deleteme4214599935706768614.txt is 82830 bytes long.
File /tmp/deleteme4214599935706768614.txt is 94644 bytes long.
File /tmp/deleteme4214599935706768614.txt is 106524 bytes long.
File /tmp/deleteme4214599935706768614.txt is 118338 bytes long.
File /tmp/deleteme4214599935706768614.txt is 130218 bytes long.
File /tmp/deleteme4214599935706768614.txt is 132000 bytes long.
Finished

答案 2 :(得分:-1)

尝试使用long值:

long byt = file.length();

答案 3 :(得分:-1)

首先, byt 必须很长。如果你询问设备目录的长度,可能会发生另一件事。对于常规文件,这是正确的方法,只需将变量更改为正确的类型。