0

バイナリファイルから文字列を読み書きするにはどうすればよいですか?

writeUTF/ (DataOutputStream/DataInputStream)を使用してみましreadUTFたが、面倒でした。

ありがとう。

4

2 に答える 2

4

FileWriter、DataOutputStream のことはしばらく忘れてください。

  • バイナリ データの場合はOutputStreamInputStreamクラスを使用します。彼らは処理しbyte[]ます。
  • テキストデータの場合、クラスを使用ReaderWriterます。String内部で Unicode を使用するため、あらゆる種類のテキストを格納できるものを処理します。

テキストからバイナリ データへのクロスオーバーは、エンコーディングを指定することで実行できます。デフォルトは OS エンコーディングです。

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

したがって、String を避けて使用したい場合byte[]は、256 バイトの値すべてを任意の順序でカバーするエンコーディングを悪用する必要があります。「UTF-8」ではなく、おそらく「windows-1252」(「Cp1252」とも呼ばれます)。

ただし、内部的には変換が行われ、ごくまれに問題が発生する場合があります。たとえばé、Unicode では、1 つまたは 2 つのコードe+ ダイアクリティカルマークの右アクセントを組み合わせることができます'。そのための変換関数(java.text.Normalizer)が存在します。

これがすでに問題を引き起こしている 1 つのケースは、異なるオペレーティング システムでのファイル名です。MacOS には Windows とは別の Unicode 正規化があるため、バージョン管理システムでは特別な注意が必要です。

したがって、原則として、より扱いにくいバイト配列、ByteArrayInputStream、または java.nio バッファを使用することをお勧めします。Stringcharは 16 ビットであることにも注意してください。

于 2012-07-20T20:09:33.543 に答える
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
于 2012-07-20T18:11:06.000 に答える