我正在我的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);
}
Run Code Online (Sandbox Code Playgroud)
我已经采取了test.txt中的支持
你好,世界.而不是12它显示14 ..为什么2额外的chacter?
那是因为在你的文件中你有"Hello World"PLUS另外两个字符: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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
250 次 |
| 最近记录: |