Hey, I have an assignment to :write a program that reads a file and writes a copy of the file to another file with line numbers inserted. I am not sure what to do at the end of the code at the "for(int i =0; i < lines.length; i++)" part. what do I need to do for the "lines" part and how do I add the line numbers?

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Question43 
public static void main(String[] args) throws IOException
    Scanner fileIn = new Scanner(new File("Chapter 11Assign43.txt") );

    FileWriter fileOut = new FileWriter("FileOut.txt");
    PrintWriter output = new PrintWriter(fileOut);

    String []array = new String[10];

    int indx = 0;
    while(fileIn.hasNext( ) )
        array[indx] = fileIn.nextLine( );


    int num = 1;
    for(int i =0; i < lines.length; i++)
3 Years
Discussion Span
Last Post by bguild

does this code do atleast some part of what you hoped it would? since your reading from a file , bufferedReader is a faster way of doing things.

a part of a code i wrote for parsing purposes :

        try {
            is = new BufferedReader(new FileReader(fileName));
            while ((line = is.readLine()) != null) {
                String[] parsedLine = line.split(" ");
                wordCount += parsedLine.length;
        } catch (IOException e) {
        } finally {

here , the condition in the while() loop takes care of checking if the end has been reached , and the split method keeps each word of each line in an array of strings.

so since you want to output each line , print the lineCount followed by the line read through the readLine() method of buffered reader. since you dont have to worry about word counts, you can omit the lines where the split() has been used. and just use a print statement and print the line.

Edited by somjit{}


Don't forget to close your output writer. If you fail to close it then your output file may be incomplete or otherwise corrupted because the writer expects to be closed before it needs to finish writing the file.

PrintWriter can take a file name directly. You don't need to wrap your PrintWriter around a FileWriter.

Your array can only hold ten lines of the file and you are storing all of the lines as the first array element.

If I understand your project correctly you have no need to use an array or any other data structure to store the file. You can read the input file and write the output file at the same time, just counting up the line numbers and inserting them into the output as you go.

Edited by bguild

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.