Ask Question
24 February, 06:23

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

+3
Answers (1)
  1. 24 February, 06:51
    0
    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 ("/n");

    }

    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 ();

    }

    }

    }
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “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 ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers