write string content to a file java

Example:

package com.w3spoint;
 
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.
Please follow and like us:
Content Protection by DMCA.com