2012-07-20 97 views
0

如何從二進制文件寫入/讀取字符串?讀取/寫入帶有字符串的BINARY文件?

我試過使用writeUTF/readUTF(DataOutputStream/DataInputStream),但它太麻煩了。

謝謝。

+0

如果您正在使用Java 7,請查看新的[Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html)類。 – Chris911 2012-07-20 18:02:13

+0

令我嫉妒,但Java 7讓我與許多較舊的程序不兼容,我寧願以另一種方式做。 – 2012-07-20 18:04:26

+1

向我們展示您迄今爲止所嘗試的內容以及您遇到錯誤/問題的位置。 – Chris911 2012-07-20 18:05:49

回答

2

忘掉的FileWriter,DataOutputStream類一會兒。

  • 對於二進制數據,一個使用OutputStreamInputStream類。他們處理byte[]
  • 對於文本數據,使用ReaderWriter類。他們處理String,它可以存儲所有類型的文本,因爲它在內部使用Unicode。

從文本到二進制數據的交叉可以通過指定編碼完成,默認爲OS編碼。

  • new OutputStreamWriter(outputStream, encoding)
  • string.getBytes(encoding)

所以,如果你想避免byte[]和使用字符串必須濫用涵蓋以任意順序全部256個字節值的編碼。所以沒有「UTF-8」,但可能是「windows-1252」(也稱爲「Cp1252」)。

但內部存在轉換,在極少數情況下可能會發生問題。例如é可以在Unicode中是一個代碼,或者兩個,e +結合變音標記右側口音'。有一個轉換函數(java.text.Normalizer)。

導致問題的一種情況是不同操作系統中的文件名; MacOS有另一個Unicode規範化比Windows,因此在版本控制系統中需要特別注意。

所以原則上最好使用更繁瑣的字節數組或ByteArrayInputStream或java.nio緩衝區。請注意,字符串char s是16位。

2

如果你想寫文字,你可以使用作家和讀者。

您可以使用Data * Stream writeUTF/readUTF,但字符串長度不得超過64K個字符。


public static void main(String... args) throws IOException { 
    // generate a million random words. 
    List<String> words = new ArrayList<String>(); 
    for (int i = 0; i < 1000000; i++) 
     words.add(Long.toHexString(System.nanoTime())); 

    writeStrings("words", words); 
    List<String> words2 = readWords("words"); 
    System.out.println("Words are the same is " + words.equals(words2)); 
} 

public static List<String> readWords(String filename) throws IOException { 
    DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(filename))); 
    int count = dis.readInt(); 
    List<String> words = new ArrayList<String>(count); 
    while (words.size() < count) 
     words.add(dis.readUTF()); 
    return words; 
} 

public static void writeStrings(String filename, List<String> words) throws IOException { 
    DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filename))); 
    dos.writeInt(words.size()); 
    for (String word : words) 
     dos.writeUTF(word); 
    dos.close(); 
} 

打印

Words are the same is true 
+0

我已經在使用writeUTF/readUTF - 它太麻煩了。我有沒有提到我想讀取/寫入二進制文件而不是純文本?抱歉...編輯主帖 – 2012-07-20 19:49:03

+0

我無法想象使用writeUTF/readUTF更簡單。沒有看到你的代碼,我無法想象你是什麼原因引起麻煩。 – 2012-07-20 20:01:10