Q:

Java program to write content into file using FileOutputStream

belongs to collection: Java File Handling Programs

0

This program will write the content into the file using FileOutputStream class. In this program we are using FileOutputStream.write() method which writes the value in bytes, so we have to convert String data into bytes.

  • String.getBytes() - returns the bytes array.
  • FileOutputStream.flush() - Is used to clear the output steam buffer.
  • FileOutputStream.close() - Is used to close output stream (Close the file).
  •  

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Write Content into File using FileOutputStream in Java

// Java program to write content into file 
// using FileOutputStream.

import java.io.File;
import java.io.FileOutputStream;
import java.util.Scanner;

public class WriteFile {
  public static void main(String args[]) {
    final String fileName = "file1.txt";

    try {
      File objFile = new File(fileName);
      if (objFile.exists() == false) {
        if (objFile.createNewFile()) {
          System.out.println("File created successfully.");
        } else {
          System.out.println("File creation failed!!!");
          System.exit(0);
        }
      }

      //writting data into file
      String text;
      Scanner SC = new Scanner(System.in);

      System.out.println("Enter text to write into file: ");
      text = SC.nextLine();

      //object of FileOutputStream
      FileOutputStream fileOut = new FileOutputStream(objFile);
      //convert text into Byte and write into file
      fileOut.write(text.getBytes());
      fileOut.flush();
      fileOut.close();
      System.out.println("File saved.");
    } catch (Exception Ex) {
      System.out.println("Exception : " + Ex.toString());
    }
  }
}

Output:

    
Enter text to write into file: 
Java is a platform independent language.
File saved.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java File Handling Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to read content from file using FileI... >>
<< Java program to create a new file...