如果之前有問題,我很抱歉。我正在嘗試使用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
輸出文件,這是我期待看到:
java的文本是utf 16 http://java.sun.com/javase/technologies/core/basic/intl/faq.jsp#text-representation 因此可能在代碼中做了一些錯誤 – 2011-05-31 17:58:44
向我們顯示您的代碼,並讓我們知道您如何嘗試處理該文件。 – Thor 2011-05-31 18:04:04
@Thor:代碼很大,所以不能發佈。但我正在做的是這樣的:它是一個簡單的逗號分隔的文本文件。我正在提取一些字段放入我的數據庫中。在此之前,我正在處理一些領域,例如與SimpleDateFormat,這是有問題的UTF-16LE。 – Bhushan 2011-05-31 18:47:32