1

文字列/文字データをバイトとしてファイルに書き込みたい.この変換を IO.* クラスで内部的に行いたい。文字列に対して getBytes() メソッドを使用したくありません。

次の 2 つの Programs を試しましたが、どちらも Character としてデータを書き込んでいます。そして、メモ帳でファイルを開くと、これらの文字を読むことができます。データをバイトとして保存するにはどうすればよいですか?

     import IO.FileWrite;

         import java.io.*;

        public class CharToChar {

private final String data;

public CharToChar(String data){
    this.data = data;
}

public static void main(String[] args) throws IOException {
    final CharToChar charToChar = new CharToChar("I am Manish");
    charToChar.write();
}

private void write() throws IOException {
    final File file = new File("CharToChar.txt");
    final FileWriter fileWriter = new FileWriter(file);
    final BufferedWriter bufferdWriter = new BufferedWriter(fileWriter);
    bufferdWriter.write(this.data);
    bufferdWriter.close();

}
  }


     import java.io.DataOutputStream;
     import java.io.FileOutputStream;
       import java.io.IOException;

       public class WriteStringAsBytesToFile {

public static void main(String[] args) {

    String strFilePath = "WriteStringAsBytes.txt";

    try
    {
        //create FileOutputStream object
        FileOutputStream fos = new FileOutputStream(strFilePath);

  /*
   * To create DataOutputStream object from FileOutputStream use,
   * DataOutputStream(OutputStream os) constructor.
   *
   */

        DataOutputStream dos = new DataOutputStream(fos);

        String str = "This string will be written to file as sequence of bytes!";

   /*
    * To write a string as a sequence of bytes to a file, use
    * void writeBytes(String str) method of Java DataOutputStream class.
    *
    * This method writes string as a sequence of bytes to underlying output
    * stream (Each character's high eight bits are discarded first).
    */

        dos.writeBytes(str);

    /*
     * To close DataOutputStream use,
     * void close() method.
     *
     */

        dos.close();

    }
    catch (IOException e)
    {
        System.out.println("IOException : " + e);
    }

}
   }

注 - > JAVA ドキュメントによると、OutputStreamWriter OutputStreamWriter は、文字ストリームからバイト ストリームへのブリッジです。

4

3 に答える 3

0

toBytes文字列をバイトに変換することは、使用したくないメソッドの仕事であるため、要件は非常に奇妙に思えます....しかし、文字列を含む任意のJavaオブジェクトをシリアル化し、次のようにファイルに保存できます。

    try ( ObjectOutputStream oos = new ObjectOutputStream(
            new FileOutputStream( "CharToChar.txt" ) ) ) {
        // write any object to a file
        oos.writeObject( "I am Manish" );
        // another option, works for Strings and makes the String pretty much un-readable
        oos.writeBytes( "hello world" );
    } catch ( IOException e ) {
        e.printStackTrace();
    }
于 2013-09-22T09:56:06.937 に答える