[英]Reading/writing a BINARY File with Strings?
如何從二進制文件寫入/讀取字符串?
我試過使用writeUTF
/ readUTF
(DataOutputStream / DataInputStream),但這太麻煩了。
謝謝。
暫時忘掉FileWriter,DataOutputStream。
OutputStream
和InputStream
類。 他們處理byte[]
。 Reader
和Writer
類。 他們處理可存儲所有類型文本的String
,因為它內部使用Unicode。 通過指定默認為OS編碼的編碼,可以完成從文本到二進制數據的轉換。
new OutputStreamWriter(outputStream, encoding)
string.getBytes(encoding)
因此,如果要避免使用byte[]
並使用String,則必須濫用一種編碼,該編碼以任何順序覆蓋所有256個字節的值。 因此,沒有“ UTF-8”,而是“ windows-1252”(也稱為“ Cp1252”)。
但是內部會發生轉換,在極少數情況下可能會發生問題。 例如,在Unicode中, é
可以是一個代碼,也可以是兩個代碼, e
+組合變音符號“- '
。 為此存在一個轉換函數(java.text.Normalizer)。
已經導致問題的一種情況是不同操作系統中的文件名。 MacOS具有Windows之外的另一種Unicode規范化,因此在版本控制系統中需要特別注意。
因此,原則上最好使用較麻煩的字節數組或ByteArrayInputStream或java.nio緩沖區。 還要注意String char
是16位。
如果要編寫文本,則可以使用作家和讀者。
您可以使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.