file.length()显然报告了错误的文件大小



我正在使用Java代码中的文本文件,并试图找出其长度。我将文件存储在记事本,编码类型为ANSI

public static void main(String[] args) throws IOException {
    File file = new File("test.txt");
    // creates the file
    double len=file.length();
    System.out.println(len);
}

假设在test.txt中我采取了

你好世界。而不是12个显示14 ..为什么2个额外的chacter ??

那是因为在您的文件中,您拥有" Hello World"加两个字符:0x13和0x10,这些标记了"新线"one_answers"托架返回"。

只是为了显示此信息,修改代码以显示您的文件字节,您会看到:

public static void main(String[] args) throws IOException {
    File file = new File("test.txt");
    // creates the file
    long len=file.length();
    System.out.println(len);

    // byte by byte:
    FileInputStream fileStream = new FileInputStream(file);
    byte[] buffer = new byte[2048];
    int read;
    while((read = fileStream.read(buffer)) != -1) {
        for(int index = 0; index < read; index++) {
            byte ch = buffer[index];
            if(buffer[index] < 0x20) {
                System.out.format(">> char: N/A, hex: %02X%n", ch);
            } else {
                System.out.format(">> char: '%c', hex: %02X%n", (char) ch, ch);
            }
        }
    }
    fileStream.close();
}

最新更新