文字列/文字データをバイトとしてファイルに書き込みたい.この変換を 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 は、文字ストリームからバイト ストリームへのブリッジです。