2011-05-31 23 views
2

如果之前有問題,我很抱歉。我正在嘗試使用Java處理文本文件。該文本文件從MS SQLServer導出。當我在PSPad中打開它時(我可以在其中查看任何十六進制格式的文本編輯器),它告訴我我的文本文件在UTF-16LE。既然我從別人那裏得到它,這是完全可能的。如何處理使用Java的UTF-16LE編碼文本文件?或將其轉換爲ASCII?

現在我的Java程序無法處理這種格式。所以我想知道是否有什麼方法可以將我的文本文件轉換爲ASCII格式,或者進行一些預處理或其他任何操作?我可以修改文件。

任何幫助是極大的讚賞。

謝謝。

編輯1

我寫了這個程序,但預計它無法正常工作。如果我在PSPad中看到輸出文件,我可以看到每個字符都是一個2字節的字符,例如'2'是3200而不是32; 'M'是4D00,而不是4D等。雖然說輸出文件的編碼是UTF-8。我有點困惑。誰能告訴我我做錯了什麼?

public static void main(String[] args) throws Exception { 

     try { 
      // Open the file that is the first 
      // command line parameter 
      FileInputStream fstream = new FileInputStream(
        "input.txt"); 
      // Get the object of DataInputStream 
      DataInputStream in = new DataInputStream(fstream); 
      BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-16LE")); 
      String strLine; 
      // Read File Line By Line 
      while ((strLine = br.readLine()) != null) { 
       // Write to the file 
       writeToFile(strLine); 
      } 
      // Close the input stream 
      in.close(); 
     } catch (Exception e) {// Catch exception if any 
      System.err.println("Error: " + e.getMessage()); 
     } 

     System.out.println("done."); 
    } 

    static public void writeToFile(String str) { 
     try { 
      OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("output.txt", true), "UTF-8"); 
      BufferedWriter fbw = new BufferedWriter(writer); 
      fbw.write(str); 
      fbw.close(); 
     } catch (Exception e) {// Catch exception if any 
      System.err.println("Error: " + e.getMessage()); 
     } 
    } 

編輯2

下面是快照:在PSPad

輸入文件(自由十六進制查看器)在PSPad enter image description here

enter image description here

輸出文件,這是我期待看到: enter image description here

+0

java的文本是utf 16 http://java.sun.com/javase/technologies/core/basic/intl/faq.jsp#text-representation 因此可能在代碼中做了一些錯誤 – 2011-05-31 17:58:44

+0

向我們顯示您的代碼,並讓我們知道您如何嘗試處理該文件。 – Thor 2011-05-31 18:04:04

+0

@Thor:代碼很大,所以不能發佈。但我正在做的是這樣的:它是一個簡單的逗號分隔的文本文件。我正在提取一些字段放入我的數據庫中。在此之前,我正在處理一些領域,例如與SimpleDateFormat,這是有問題的UTF-16LE。 – Bhushan 2011-05-31 18:47:32

回答

6

爲字符集UTF-16LE創建一個InputStreamReader,並且您將全部設置。

+0

非常感謝bmargulies,我會嘗試一下。 – Bhushan 2011-05-31 18:48:22

1

InputStreamReader將允許您在內存中加載您的UTF-16EL。然後你可以執行你需要的所有字符串操作。然後,您可以使用OutputStreamWriter保存爲ASCII格式。使用CharSet選擇格式。

+0

非常感謝JVerstry,我會嘗試一下。 – Bhushan 2011-05-31 18:47:52

相關問題