Write String as bytes to a file using DataOutputStream
- /*
- Write String as bytes to a file using DataOutputStream
- This Java example shows how to write a Java String value to a file
- as a sequence of bytes using writeBytes method of Java
- DataOutputStream class.
- */
- import java.io.DataOutputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- public class WriteStringAsBytesToFile {
- public static void main(String[] args) {
- String strFilePath = "C://FileIO//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);
- }
- }
- }



