Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

Create a program which takes input from the console and writes to a file using FileWriter

  1. /*
  2. Create a program which takes input from the console and writes to a file using FileWriter.
  3. */
  4.  
  5. import java.io.*;
  6. class FileWriterDemo
  7. {
  8.  public static void main(String args[])
  9.  {
  10.   try
  11.   {
  12.    DataInputStream in = new DataInputStream(System.in);
  13.    FileWriter fw = new FileWriter("C:/IO_demo.txt");
  14.    
  15.    System.out.println("How many lines?");
  16.    int numberOfLines = Integer.parseInt(in.readLine());
  17.    String line = "";
  18.    
  19.    for(int i = 0; i < numberOfLines; i++)
  20.    {
  21.     line = in.readLine();
  22.     fw.write(line + "\n"); // throws IOException
  23.    }
  24.    fw.close();
  25.   }
  26.   catch(Exception e)
  27.   {
  28.    System.out.println("Exception :  " + e );
  29.   }
  30.  }
  31. }
No votes yet
Share this

Post new comment