我正在我的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 个字符??
最佳答案
那是因为在你的文件中有“Hello World”加上另外两个字符:0x13 和 0x10,它们标记“换行符”和“回车符”。
为了展示这一点,请修改您的代码以逐字节显示您的文件,您将看到:
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();
}
关于java - File.length() 显然报告了错误的文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22259186/