JAVA IO讀取文件會產生多餘的字符讀取問題!

    在讀取文件時,通過這種批量讀取時,發生了多讀取了字符;

    源文件:

   

 而實際操作讀取如下:

public static void main(String[] args) {

        //文件路徑
        File file =new File("phone.xml");

        //系統平臺的編碼是utf-8
       // System.out.println(System.getProperty("file.encoding"));

        //
        System.out.println("文件大小:"+file.length());

        int len=0;

        //中轉站
        char[] ch=new char[100];

        //文件讀取對象
        try (FileReader reader = new FileReader(file) ){

            //讀取一個
//            len= reader.read();
//            System.out.println((char)len);

            //批量讀取
//            len =reader.read(ch);
//            System.out.println(ch);

            int count=0;

            //循環輸出
            while((len =reader.read(ch))!=-1 ) {
              System.out.println("第"+count+"次"+len);
              System.out.println(ch);
                // 必須用字符串方法指定實際大小
              //System.out.println(new String(ch, 0, len));

              count++;  //累計
            }

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

效果:

原因:

//中轉站
char[] ch=new char[100];
while((len =reader.read(ch))!=-1 ) {
  System.out.println(ch);  //這個是問題的關鍵,雖然是45個字符,但ch是要輸出100個字符,那麼就會向上讀取滿100個;
}

解決:必須指定實際的大小!!!

 while((len =reader.read(ch))!=-1 ) {
  // 必須用字符串方法指定實際大小
  System.out.println(new String(ch, 0, len));
}

 

效果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章