Sunday, September 11, 2011

Java code to write to a file

This sample java code will show how to write to a file. We will use the class FileWriter and BufferedWriter to write to a file.

Java Source Code

Note : While making instance of FileWriter we provide path (at your local machine) in its constructor where we want to create and write file. Please make sure that path is correct otherwise code will throw "The system cannot find the path specified" error.

public class WriteFile
 public static void main(String args[])
  // Provide path where you want to create and write file
  FileWriter fstream = new FileWriter("C:\\out.txt");
  BufferedWriter out = new BufferedWriter(fstream);
  // Write to file
  out.write("Hello Java World !");
  //Close the output stream
  }catch (Exception e){
            //Catch exception if any            
    System.err.println("Error: " + e.getMessage());

0 Responses to “Java code to write to a file”

Post a Comment

© 2011 • All rights reserved.
Blogger Template by Bloggermint