Java 输入流读取文本文件换行符问题
2024-10-11 23:31:17
一问题
在学习流编程的过程中,我遇到了一下问题。首先来看一下我写的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’,在对文件字符进行统计与编码时,应特别注重该问题。
最新文章
- go语言常用函数:cap
- MYSQL 免安装版(windows 7/64)
- Dom初
- 移位操作<;<;和>;>;,是逻辑数字上的移动(和大端小端无关)
- C#中Split函数的使用
- Beta Round #9 (酱油杯noi考后欢乐赛)随机数生成器
- js 高级函数 之示例
- 深入浅出Node.js (附录B) - 调试Node
- hdu1754(splay)
- POJ-1915 Knight Moves (BFS)
- java配置环境及安装
- Django中的模板渲染是什么
- tp5.1中的容器和facade的实现
- A - The Water Problem
- redis主从复制详述
- css 背景图片自适应元素大小
- IT蓝豹强烈推荐:符合1-2年工作经验,开发中的难点及相关优化:
- “The operation cannot be completed because the DbContext has been disposed” exception with lazy load disabled
- memcached注意事项与应用范围、应用条件、限制
- POJ 2139 Six Degrees of Cowvin Bacon (floyd)