Friday, 16 January 2015

File Structures - Java Program to create a new file and write data to it.


This is a Java Program which creates a  new file and writes data to it.

Here we use FileOutputStream class and OutputStreamWriter classes to write the data into the file.

PROGRAMS :
package codingcorner.in;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class FileOpeningWriting {
 public void fileWriting() {
  try {
   
   File newFile = new File("sample.txt");
   FileOutputStream is = new FileOutputStream(newFile);
   OutputStreamWriter osw = new OutputStreamWriter(is);
   Writer w = new BufferedWriter(osw);
   w.write("Hello this is a sample file.");
   w.close();
  } catch (IOException e) {
   System.err.println("Problem writing to the file");
  }
 }

 public static void main(String[] args) {
  FileOpeningWriting write = new FileOpeningWriting();
  write.fileWriting();
 }
}

OUTPUT :



No comments:

Post a Comment