Note that there are some explanatory texts on larger screens.

plurals
  1. POFile Write : String to Bytes
    text
    copied!<p>I want to write string/Char data as bytes in a file.I want this conversion happen internally in IO.* classes. I do not want to use getBytes() method on string.</p> <p>I tried following two Programs but both are writing data as Character . And when i open the file in notepad i can read these characters. How can i store my data as bytes ?</p> <pre><code> 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); } } } </code></pre> <p>Note - > JAVA docs says OutputStreamWriter An OutputStreamWriter is a bridge from character streams to byte streams: * Characters written to it are encoded into bytes using a specified.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload