Java file output stream several ways to write files

  • 2020-04-01 03:14:56
  • OfStack

The Java file output stream is a byte stream class used to process raw binary data. In order to write data to a file, the data must be converted into bytes and saved to a file.


package com.yiibai.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteFileExample {
 public static void main(String[] args) {
  FileOutputStream fop = null;
  File file;
  String content = "This is the text content";
  try {
   file = new File("c:/newfile.txt");
   fop = new FileOutputStream(file);
   // if file doesnt exists, then create it
   if (!file.exists()) {
    file.createNewFile();
   }
   // get the content in bytes
   byte[] contentInBytes = content.getBytes();
   fop.write(contentInBytes);
   fop.flush();
   fop.close();
   System.out.println("Done");
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (fop != null) {
     fop.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}
//The updated JDK7, for example, USES a new "try resource close" approach to ease handling files.
package com.yiibai.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteFileExample {
 public static void main(String[] args) {
  File file = new File("c:/newfile.txt");
  String content = "This is the text content";
  try (FileOutputStream fop = new FileOutputStream(file)) {
   // if file doesn't exists, then create it
   if (!file.exists()) {
    file.createNewFile();
   }
   // get the content in bytes
   byte[] contentInBytes = content.getBytes();
   fop.write(contentInBytes);
   fop.flush();
   fop.close();
   System.out.println("Done");
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}


Related articles: