2011-05-31 21 views

回答

2

如果您使用的是writeUTF(),那麼您應該閱讀它的JavaDoc以瞭解它總是寫入modified UTF-8

如果您想使用其他編碼,那麼您必須「手動」執行編碼,並以某種方式存儲byte[]的長度。

例如:

RandomAccessFile raf = ...; 
String writeThis = ...; 
byte[] cp1250Data = writeThis.getBytes("cp1250"); 
raf.writeInt(cp1250Data.length); 
raf.write(cp1250Data); 

閱讀將同樣的工作:

RandomAccessFile raf = ...; 
int length = raf.readInt(); 
byte[] cp1250Data = new byte[length]; 
raf.readFully(cp1250Data); 
String string = new String(cp1250Data, "cp1250"); 
+0

我得到?ÄŐđŔ×U代替ČŽŠĐčžšđ的。 'byte [] name = new byte [NAME_LEN]; len = raf.read(name); System.out.println(「Name:」+ new String(name,「cp1250」));' – Gogoo 2011-05-31 10:29:54

+0

@Gogoo:你沒有使用我發佈的代碼。 – 2011-05-31 10:37:20

+0

@Gogoo:那麼這表明該文件不在您認爲的編碼中。文件從哪裏來?您是如何瞭解其編碼的? – 2011-05-31 10:44:12

0

此代碼將使用1250的代碼頁寫和讀的字符串。當然,你需要進行清潔時,投入督促之前好好檢查異常和關閉流:)

public static void main(String[] args) throws Exception { 
    File file = new File("/toto.txt"); 
    String myString="This is a test"; 
    OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("windows-1250")); 
    w.write(myString); 
    w.flush(); 
    CharBuffer b = CharBuffer.allocate((int)file.length()); 
    new InputStreamReader(new FileInputStream(file), Charset.forName("windows-1250")).read(b); 
    System.out.println(b.toString()); 
} 
相關問題