2016-02-23 75 views
0

因此,我應該在UTF-16編碼的文件中插入信息,而不是一些操作(計數行,單詞等)。問題是,如果我選擇UTF-16編碼,則會引發異常,但UTF-8正常工作。以UTF-16編寫的文件無法打開,但UTF-8可以

import java.io.*; 
import java.util.Scanner; 

public final class Q4 { 
    public static void main(String[ ] args)throws FileNotFoundException{ 
     final String ENCODING = "UTF-16"; 
     final String FILE = " testcount"; 
     PrintWriter out = null; 
// Given code – do not modify(!) This will create the UTF-16 test file on your drive. 
     try { 
      out = new PrintWriter(FILE, ENCODING); 
      out.write("Test file for UTF-16\n" + "(contains surrogate pairs:\n" + 
        "Musical symbols in the range 1D100–1D1FF)\n\n"); 
      out.write("F-clef (1D122): \uD834\uDD22\tCrotchet (1D15F): \uD834\uDD5F\n"); 
      out.write("G-clef (1D120): \uD834\uDD20\tSemiquaver (1D161): \uD834\uDD61\n"); 
      out.write("\n(? lines, ?? words, ??? chars but ??? code points)\n"); 
     } catch (IOException e) { System.out.println("uh? cannot write to file!"); 
     } finally { if (out != null) out.close(); 
     } 
// Your code – scan the test file and count lines, words, characters, and code points. 

     Scanner fin = new Scanner(new File(FILE)); 
     String s = ""; 

     //get the data in file 
     while (fin.hasNext()){ 
      s = s + fin.next();  
      System.out.println(s);    
     } 

     fin.close(); 

     //count words and lines 



    } 
} 

我唯一的猜測,一個遙不可及的一個,就是它必須是與該操作系統(Windows 8.1)不能夠保存UTF-16代碼,但聽起來像一個愚蠢的猜測。

+6

而例外的是......? –

+0

是的,它拋出了一個異常。你指的是什麼? –

+2

我在問這是什麼例外。此刻,就好像你要去看醫生一樣,說「我有什麼不對勁」,但沒有再給出任何症狀。 (提示:改變'catch'塊打印出'e' ...) –

回答

1

當你讀文件指定編碼:

Scanner fin = new Scanner(new File(FILE), ENCODING); 
+0

你是一個簡單的頭腦,謝謝隊友救生員:) –

相關問題