文件写入:字符串到字节

Hak*_*ata 1 java file-io file java-io

我想在文件中将字符串/字符数据写为字节.我希望这种转换在IO.*类内部发生.我不想在字符串上使用getBytes()方法.

我尝试了两个程序,但都将数据写为字符.当我在记事本中打开文件时,我可以阅读这些字符.如何将数据存储为字节?

     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);
    }

}
   }
Run Code Online (Sandbox Code Playgroud)

注 - > JAVA文档说OutputStreamWriter OutputStreamWriter是从字符流到字节流的桥接器:*写入它的字符使用指定的字节编码为字节.

roc*_*boy 5

我认为你有关写字节/字符的错误观念.字符只是字节数据的表示.该表示基于字符编码类型来决定.看下面的代码:

OutputStream os = new FileOutputStream(filePath);
    os.write("This is byte date".getBytes("UTF-8"));
    os.close();
Run Code Online (Sandbox Code Playgroud)

如果在运行上面的代码片段后打开文件,您会注意到文件中的相同字符串.您的文件始终以字节为单位.字节由文本编辑器读取,并根据其默认字符编码进行编码,通常为UTF-8,但并非总是如此.