Java FileOutputStream : Byte Streams
In the last chapter we have seen the FileInputStream and now in this chapter we will be learning about FileOutputStream.
Java FileOutputStream : Byte Streams
- FileOutputStream is used to write bytes to the file.
- The Java.io.FileOutputStream class is used to write bytes to the file
- FileOutputStream is usually used for writing content to the file
Program : Java FileOutputStream - Byte Streams
package com.c4learn.stream; import java.io.*; class WriteFile { public static void main(String args[]) { try { String msg = "Java is Easy and Simple."; FileOutputStream fout = new FileOutputStream("src/files/output.txt"); byte ch[] = msg.getBytes(); fout.write(ch); fout.close(); System.out.println("String written to File"); } catch (Exception e) { System.out.println(e); } } }
Output :
String written to File
and File contents of output.txt -
Java is Easy and Simple.
Explanation :
We have created one object for FileOutputStream class which is used to write stream of data to file.
FileOutputStream fout = new FileOutputStream("src/files/output.txt");
Now we need to read the content of the string and copy them into the byte array. getBytes() method encodes string into a sequence of bytes and stores the result into a new byte array.
byte ch[] = msg.getBytes();
After that we need to write the content to the file using following line of code -
fout.write(ch);