2016-04-21 93 views
1
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); 

} 

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

考虑到xxx.txt包含:

a 
b b 
cccd 

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

谢谢。

回答

2
  • 这是因为窗使用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:Atari 8位机器使用ATCCII变体的ASC II(十进制155)
  • CR + LF:Microsoft Windows,DOS(MS-DOS,PC DOS等),DEC TOPS-10,RT-11,CP/M,MP/M,Atari TOS,OS/2,Symbian操作系统,Palm OS,Amstrad CPC, 和大多数其他早期的非Unix和非IBM操作系统
  • LF + CR:Acorn BBC和RISC OS假脱机文本输出。

因此,根据操作系统家族的不同,总结行编码不同。

0

我测试了你的方法一个新行被认为不是一个单一的字符其实际上被认为是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()); 
相关问题