Java:为什么在读取文本文件的情况下\ n被认为是2个字符? [英] Java: Why is \n considered 2 characters in a read text file situation?
本文介绍了Java:为什么在读取文本文件的情况下\ n被认为是2个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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包含:
Considering that xxx.txt contains:
a
b b
cccd
我只是对为什么下一行"被认为是2个字符感到困惑?我手动计算了10个字符(包括空格),但结果是12.
I'm just confused at why "next line" is considered 2 characters? I manually counted 10 characters (including white space) but the result is a 12.
谢谢.
推荐答案
- 这是因为Windows使用2个字符
\ r \ n
转到了新行,即\ r
(回车)和\ n
(换行符) 基于 - * nix(类似于Unix)的系统(例如BSD,Linux)仅将
\ n
用于换行符 - Mac仅使用
\ r
- It is because windows uses 2 characters
\r\n
to go to a new line i.e\r
(carriage return) and\n
(newline feed) - *nix (Unix like) based systems such as BSD, Linux use only
\n
for newline - Mac uses only
\r
- LF:Multics,Unix和类似Unix的系统(Linux,OS X,FreeBSD,AIX,Xenix等),BeOS,Amiga,RISC OS等
- CR:准将8位计算机,Acorn BBC,ZX Spectrum,TRS-80,Apple II家族,Oberon,Mac OS OS 9及更高版本
- RS:QNX 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假脱机文本输出.
回车将光标移动到行的开头,而 \ n
将光标移动到下一行.
Carriage return moves the cursor to the beginning of the line whereas \n
moves the cursor to the next line.
引自Wikipedia( https://en.wikipedia.org/wiki/Newline ):
Quoting from Wikipedia(https://en.wikipedia.org/wiki/Newline):
因此,根据OS系列的不同,得出行编码的结论也会有所不同.
Hence to conclude line encoding differ as per the OS family.
这篇关于Java:为什么在读取文本文件的情况下\ n被认为是2个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文