Java 輸入流讀取文本文件換行符問題


一問題

在學習流編程的過程中,我遇到了一下問題。首先來看一下我寫的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’,在對文件字符進行統計與編碼時,應特別注重該問題。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM