Tutorialspoint examples

Learn java tutorial with examples for beginners online

write byte content to a file java program


Example:

package com.tutorialspointexamples;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
 
public class WriteByteToFileTest {
  public static void main(String args[]){
	  OutputStream opStream = null;
      try {
          String strContent = "Test Content";
          byte[] byteContent = strContent.getBytes();
          File myFile = new File("D:/Test files/test.txt");
          //check if file exist, 
          //otherwise create the file before writing
          if (!myFile.exists()) {
              myFile.createNewFile();
          }
          opStream = new FileOutputStream(myFile);
          opStream.write(byteContent);
          opStream.flush();
      } catch (Exception e) {
          e.printStackTrace();
      } finally{
          try{
              if(opStream != null) {
            	  opStream.close();
            	  System.out.println("Successfully write "
            	  		+ "byte content to file.");
              }
          } catch(Exception ex){
        	  ex.printStackTrace();
          }
      }
  }
}

Output:

Stored data in temporary file.
Successfully write byte content to file.

Download this example.

Download tutorialspointexamples Android App
Copyright © 2018 Tutorialspoint examples DMCA.com Protection Status