Programming Tutorials

A Java program which takes contents of one file and sends the output to another file by adding line numbers to each line.

By: Ganesh Iyer in Java Tutorials on 2009-06-03  

In this tutorial I will explain about File I/O functionality concept in JAVA. In this example, I have a file named compare.java which I want to write to a file  named out.txt with the line numbers prefixed to each line.

/* Author      - Ganesh Iyer Contact No (0)9176148207
  Program     - 
  Written on  - 03-06-2009 */


import java.io.*;

class Finputoutput{

   public static void main(String[] args) throws Exception
    {

     //Check for two arguments

     if(args.length != 2)

     {
     System.out.println(\"To execute the program
provide two parameters <INPUT> <SPACE> <OUTPUT> Files
\");
     System.exit(1);
      }

     String fname = args[0], wname = args[1], str;

     int counter=0;

     FileReader f = new FileReader(fname);
     BufferedReader in = new BufferedReader(f);

     FileWriter fw = new FileWriter(wname);


     while ((str=in.readLine()) != null)

      {
             counter++;
             fw.write(counter+\"
\"+str+\"\\n\");
             System.out.println(counter+\"
\"+str);
          }

         f.close();
         fw.close();

      }

}

To Execute - java Finputoutput <INPUT> <SPACE> <OUTPUT> Example    -  java Finputoutput compare.java out.txt

Output

1 class compare
2 {
3    public static void main(String[] args)
4    {
5       numcompare comparenum = new numcompare();
6       comparenum.threenumcompare();
7    }
8 }
9
10 class numcompare
11 {
12    void threenumcompare()
13    {
14
15          int a = 1;
16          int b = 2;
17          int c = 3;
18
19         if ((a>b)&&(c<a))
20          {
21              System.out.println(\"a
is gt b&c\");
22           }
23         else if ((b>a) &&
(c<b))
24           {
25              System.out.println(\"b
is gt a&c\");
26           }
27         else
28           {
29              System.out.println(\"c
is gt a&b\");
30          }
31     }
32 }





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)