gpt4 book ai didi

Java:为什么在读取文本文件的情况下\n 被认为是 2 个字符?

转载 作者:行者123 更新时间:2023-11-29 04:46:59 25 4
gpt4 key购买 nike

import java.io.*;

public class xxx {

public static void main(String[] args) throws IOException {
FileReader fs = new FileReader("xxx.txt");
int t = fs.read();
int count = 0;

while (t!=-1) {
count++;
t = fs.read();
}
System.out.println(count);

}

考虑到 xxx.txt 包含:

a
b b
cccd

我只是对为什么“下一行”被认为是 2 个字符感到困惑?我手动计算了 10 个字符(包括空格),但结果是 12。

谢谢。

最佳答案

  • 这是因为 windows 使用 2 个字符 \r\n 去换行即\r(回车)和\n(换行符)
  • *nix(类 Unix)系统,如 BSD、Linux 仅使用 \n 换行
  • Mac 仅使用 \r

回车将光标移动到行首,而 \n 将光标移动到下一行。

引自维基百科(https://en.wikipedia.org/wiki/Newline):

  • LF: Multics, Unix and Unix-like systems (Linux, OS X, FreeBSD, AIX, Xenix, etc.), BeOS, Amiga, RISC OS, and others
  • CR: Commodore 8-bit machines, Acorn BBC, ZX Spectrum, TRS-80, Apple II family, Oberon, Mac OS up to version 9, and OS-9
  • RS: QNX pre-POSIX implementation
  • 0x9B: Atari 8-bit machines using ATASCII variant of ASCII (155 in decimal)
  • CR+LF: Microsoft Windows, DOS (MS-DOS, PC DOS, etc.), DEC TOPS-10, RT-11, CP/M, MP/M, Atari TOS, OS/2, Symbian OS, Palm OS, Amstrad CPC, and most other early non-Unix and non-IBM OSes
  • LF+CR: Acorn BBC and RISC OS spooled text output.

因此得出结论,行编码因操作系统系列而异。

关于Java:为什么在读取文本文件的情况下\n 被认为是 2 个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36760209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com