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 Printer Friendly Format
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 }
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Archived Comments
1. i just got to know about this and i am really imp
View Tutorial By: spo_mega at 2009-06-11 07:16:38
2. how to run file IO program?
isn't that must
View Tutorial By: farah at 2009-08-24 02:41:59