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 BufferedWriter

  1. /*
  2.  * Create a program which takes input from the console and writes to a file using BufferedWriter.
  3.  */
  4. import java.io.*;
  5. class BufferedWriterDemo
  6. {
  7.  public static void main(String args[])
  8.  {
  9.   try
  10.   {
  11.    DataInputStream in = new DataInputStream(System.in);
  12.    FileWriter fw = new FileWriter("C:/IO_demo.txt");
  13.    BufferedWriter bw = new BufferedWriter(fw);
  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.     bw.write(line + "\n"); // throws IOException
  23.    }
  24.    
  25.    bw.close();
  26.    
  27.   }
  28.   catch(Exception e)
  29.   {
  30.    System.out.println(" Exception : " + e);
  31.   }
  32.  }
  33. }
No votes yet
Share this

Post new comment