ADVERTISEMENT
ADVERTISEMENT

Java program to write content into file using FileOutputStream

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).

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.

Java File Handling Programs »


ADVERTISEMENT




ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.