【问题标题】:Java: Why is \n considered 2 characters in a read text file situation?Java:为什么在读取文本文件的情况下 \n 被视为 2 个字符?
【发布时间】:2016-08-14 02:24:34
【问题描述】:
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。
谢谢。
【问题讨论】:
标签:
java
file
count
character
reader
【解决方案1】:
- 这是因为 windows 使用 2 个字符
\r\n 去换行,即
\r(回车)和\n(换行)
- *基于 nix(类 Unix)的系统,如 BSD、Linux 仅使用
\n 换行
- Mac 仅使用
\r
回车将光标移至行首,而\n 将光标移至下一行。
引自维基百科(https://en.wikipedia.org/wiki/Newline):
- LF:Multics、Unix 和类 Unix 系统(Linux、OS X、FreeBSD、AIX、Xenix 等)、BeOS、Amiga、RISC OS 等
- CR:Commodore 8 位机器、Acorn BBC、ZX Spectrum、TRS-80、Apple II 系列、Oberon、Mac OS 最高版本 9 和 OS-9
- RS:QNX pre-POSIX 实施
- 0x9B:使用 ASCII 的 ATASCII 变体(十进制为 155)的 Atari 8 位机器
- CR+LF:Microsoft Windows、DOS(MS-DOS、PC DOS 等)、DEC TOPS-10、RT-11、CP/M、MP/M、Atari TOS、OS/2、Symbian OS、 Palm OS、Amstrad CPC、
以及大多数其他早期的非 Unix 和非 IBM 操作系统
- LF+CR:Acorn BBC 和 RISC OS 假脱机文本输出。
因此得出结论,行编码因操作系统系列而异。
【解决方案2】:
我测试了你的方法一个新行被认为不是一个单独的字符,它实际上被认为是 2 个字符你可以在我的代码中测试这个尝试注释掉“逐行打印每个字符”的行
顺便说一句,如果您想修剪空格并实际获得字数,我已经完成了参考我的示例。在while循环中,您已经编写了它的迭代计数bt并没有给出确切的输出,将count++替换为++count。
FileReader fs = new FileReader("src/hackerrank/xxx.txt");
int t = fs.read();
int count = 0;
StringBuffer word = new StringBuffer();
List<Character> chars = new ArrayList<Character>();
while (t!=-1) {
chars.add((char)t);
++count;
t = fs.read();
}
System.out.println(count);
for (Character aChar : chars) {
//System.out.println(aChar); printing each character line by line
if (Character.isWhitespace(aChar)) {
//ignoring the white spaces
}else{
word.append(aChar);//adding the input without any whitespaces
}
}
System.out.println(word.length());