gpt4 book ai didi

java - 文件写入 : String to Bytes

转载 作者:行者123 更新时间:2023-11-29 07:06:39 31 4
gpt4 key购买 nike

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

我尝试了以下两个程序,但都将数据写入 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 是从字符流到字节流的桥梁: * 写入它的字符使用指定的编码成字节。

最佳答案

我认为您对以字节/字符形式编写的概念是错误的。字符,只是字节数据的表示。这种表示是根据 Character Encoding 决定的类型。看下面的代码:

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

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

关于java - 文件写入 : String to Bytes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18942154/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com