174k views
3 votes
Create a file with a 20 lines of text and name it "lines.txt". Write a program to read this a file "lines.txt" and write the text to a new file, "numbered_lines.txt", that will also have line numbers at the beginning of each line. Example: Input file: "lines.txt" Line one Line two Expected output file: 1 Line one 2 Line two

User Olaseni
by
6.5k points

1 Answer

6 votes

Answer:

The code has been developed in JAVA as it is the best feasible concept to handle the files.

CODE :

import java.io.*;

public class textEditor { // main class that has the code

public static void main(String[] args) { // main driver method

try {

int count = 0; // count to print the line numbers to the output file

BufferedReader br = new BufferedReader(new FileReader("lines.txt")); // reading the data from the source text file

File outfile = new File("numbered_lines.txt"); // creating a file in the output directory

FileWriter fw = new FileWriter(outfile.getAbsoluteFile()); // initialising the filewriter class to write the data

BufferedWriter bw = new BufferedWriter(fw); // appending the bufferedwriter to get the data to the output file

String line; // temporary string value

if (!outfile.exists()) { // if file doesnt exists, then create it

outfile.createNewFile();

}

while ((line = br.readLine()) != null){ // iterating over the total line in the source file

count++;

bw.write(count +" "+ line); // writing the source data with the line numbers to the output file

bw.write("\\");

}

bw.close(); // closing the file

System.out.println("Process Done"); // prompt for the user

} catch (IOException e) { // catching if any exception is raised

e.printStackTrace();

}

}

}

Step-by-step explanation:

User Alejandro Haro
by
7.0k points