Java 输入流读取文本文件换行符问题

source: http://blog.csdn.net/leixingbang1989/article/details/12195847

在学习流编程的过程中,我遇到了一下问题。首先来看一下我写的Java源程序:

[java]  view plain  copy
  1. package StreamLearn;  
  2.   
  3. import java.io.*;  
  4.   
  5. public class TestFileInputStream {  
  6.     public static void main(String[] args) {  
  7.         int count=0;  
  8.         FileInputStream in=null;  
  9.         try{  
  10.             in =new FileInputStream("c:\\a.java");  
  11.         }catch(FileNotFoundException e)  
  12.         {  
  13.             System.out.println("can not find it");  
  14.             System.exit(1);  
  15.         }  
  16.           
  17.       
  18.         long num=0;  
  19.         try{  
  20.           
  21.             while((count=in.read())!=-1){  
  22.                 System.out.print((char)count);  
  23.                 //System.out.println(count);  
  24.                 num++;  
  25.             }     
  26.            }catch(IOException e)  
  27.            {  
  28.                e.printStackTrace();  
  29.            }  
  30.            System.out.println("\n字符个数:"+num);  
  31.       }  
  32.       
  33.         
  34. }  

  该代码功能十分简单,从a.java文件中读取字符,并统计个数。让我们来看一下a.java文件中的具体内容:


 

程序的运行结果如下:

 

123

456

 

字符个数:10

问题出现,本来只有6个字符为什么会变为8个字符呢?让我们对源代码进行改进:

 

[java]  view plain  copy
  1. package StreamLearn;  
  2.   
  3. import java.io.*;  
  4.   
  5. public class TestFileInputStream {  
  6.     public static void main(String[] args) {  
  7.         int count=0;  
  8.         FileInputStream in=null;  
  9.         try{  
  10.             in =new FileInputStream("c:\\a.java");  
  11.         }catch(FileNotFoundException e)  
  12.         {  
  13.             System.out.println("can not find it");  
  14.             System.exit(1);  
  15.         }  
  16.           
  17.       
  18.         long num=0;  
  19.         try{  
  20.           
  21.             while((count=in.read())!=-1){  
  22.                 //System.out.print((char)count);  
  23.                 System.out.println(count);  
  24.                 num++;  
  25.             }     
  26.            }catch(IOException e)  
  27.            {  
  28.                e.printStackTrace();  
  29.            }  
  30.            System.out.println("\n字符个数:"+num);  
  31.       }  
  32.       
  33.         
  34. }  

运行结果如下:

49
50
51
13
10
52
53
54
字符个数:8

查询ASCII表,得知1对应ASCII值为49,一直到6为54。多出来的字符对应的ASCII值为13和10,其中13对应为归位符,10为换行符。有关归位与换行的区别请参考我的博客:

http://blog.csdn.net/leixingbang1989/article/details/12056193,在此不多介绍。

总结:

在文件中,换行需要占两个字节,分别对应‘/r’‘/n’,在对文件字符进行统计与编码时,应特别注重该问题。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值