一问题

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

package StreamLearn;

import java.io.*;

public class TestFileInputStream {
public static void main(String[] args) {
int count=0;
FileInputStream in=null;
try{
in =new FileInputStream("c:\\a.java");
}catch(FileNotFoundException e)
{
System.out.println("can not find it");
System.exit(1);
} long num=0;
try{ while((count=in.read())!=-1){
System.out.print((char)count);
//System.out.println(count);
num++;
}
}catch(IOException e)
{
e.printStackTrace();
}
System.out.println("\n字符个数:"+num);
} }

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

程序的运行结果如下:

123

456

字符个数:10

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

package StreamLearn;

import java.io.*;

public class TestFileInputStream {
public static void main(String[] args) {
int count=0;
FileInputStream in=null;
try{
in =new FileInputStream("c:\\a.java");
}catch(FileNotFoundException e)
{
System.out.println("can not find it");
System.exit(1);
} long num=0;
try{ while((count=in.read())!=-1){
//System.out.print((char)count);
System.out.println(count);
num++;
}
}catch(IOException e)
{
e.printStackTrace();
}
System.out.println("\n字符个数:"+num);
} }

运行结果如下:

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’,在对文件字符进行统计与编码时,应特别注重该问题。

最新文章

  1. go语言常用函数:cap
  2. MYSQL 免安装版(windows 7/64)
  3. Dom初
  4. 移位操作<<和>>,是逻辑数字上的移动(和大端小端无关)
  5. C#中Split函数的使用
  6. Beta Round #9 (酱油杯noi考后欢乐赛)随机数生成器
  7. js 高级函数 之示例
  8. 深入浅出Node.js (附录B) - 调试Node
  9. hdu1754(splay)
  10. POJ-1915 Knight Moves (BFS)
  11. java配置环境及安装
  12. Django中的模板渲染是什么
  13. tp5.1中的容器和facade的实现
  14. A - The Water Problem
  15. redis主从复制详述
  16. css 背景图片自适应元素大小
  17. IT蓝豹强烈推荐:符合1-2年工作经验,开发中的难点及相关优化:
  18. “The operation cannot be completed because the DbContext has been disposed” exception with lazy load disabled
  19. memcached注意事项与应用范围、应用条件、限制
  20. POJ 2139 Six Degrees of Cowvin Bacon (floyd)

热门文章

  1. python输出1到100之和的几种方法
  2. UITableViewCell 高度计算从混沌初始到天地交泰
  3. 适配----Autolayout
  4. iOS项目里面如何清理缓存
  5. 函数strtok
  6. Codevs 1001 舒适的路线 2006年 NOIP全国联赛提高组
  7. mysql5.7的安装
  8. 【转】Windows10下80端口被PID为4的System占用导致Apache无法启动的分析与解决方案
  9. Node.js:JavaScript脚本运行环境
  10. HTML5课程大纲/学习路线