文件写入:字符串到字节

时间:2013-09-22 09:12:55

标签: java file file-io 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);
    }

}
   }

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

3 个答案:

答案 0 :(得分:5)

我认为你有关写字节/字符的错误观念。字符只是字节数据的表示。该表示基于Character Encoding类型决定。请查看以下代码:

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

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

答案 1 :(得分:1)

不确定是否有任何java IO类可以执行此操作,并且我发现您不想使用getBytes(),但如果您决定采用getBytes()方式,那么您可以修改您的第一个示例中的write()方法是这样的:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Arrays;

public class CharToChar {

    private final String data;

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

    private void write() throws IOException {       
        OutputStream fos = new FileOutputStream(new File("CharToChar.txt"));
        fos.write(Arrays.toString(this.data.getBytes()).getBytes());
        fos.close();
    }

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

答案 2 :(得分:0)

您的要求似乎很奇怪,因为将String转换为字节是您不想使用的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();
    }