我想将字符串/字符数据作为字节写入文件中。我希望这种转换在 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 一个 OutputStreamWriter 是从字符流到字节流的桥梁: * 写入它的字符使用指定的编码为字节。