user3342038
user3342038

Reputation: 63

How to add line numbers to a text file?

So I need to make a program that reads a file containing text and then adds line numbers to each line. What I have so far prints out the line number but instead of just printing out each line, it prints all of the text in each line. How can I just have it so it prints out the line?

Here's the code I have so far:

public static void main(String[] args) throws FileNotFoundException {
    try {
        ArrayList<String> poem = readPoem("src\\P7_2\\input.txt");
        number("output.txt",poem);
    }catch(Exception e){
        System.out.println("File not found.");
    }
}

public static ArrayList<String> readPoem(String filename) throws FileNotFoundException {
    ArrayList<String> lineList = new ArrayList<String>();
    Scanner in = new Scanner(new File(filename));
    while (in.hasNextLine()) {
        lineList.add(in.nextLine());
    }
    in.close();
    return lineList;
}
public static void number (String filename,ArrayList<String> lines) throws FileNotFoundException{
    PrintWriter out = new PrintWriter(filename);
    for(int i = 0; i<lines.size(); i++){
        out.println("/* " + i + "*/" + lines);
    }
    out.close();
}

Upvotes: 0

Views: 4277

Answers (3)

darthVader
darthVader

Reputation: 41

i'd say this is your problem:

out.println("/* " + i + "*/" + lines); //this prints all the lines each loop execution

you can try using:

int i = 1; //or the first value you wish
for(String a : lines){
    out.println("/* " + i + "*/" + a);
    i++;
}

Upvotes: 0

fge
fge

Reputation: 121740

Here is a shorter version of your program using new capabilities offered by Java 7; it supposes that you have a short enough source file:

final Charset charset = StandardCharsets.UTF_8;
final String lineSeparator = System.lineSeparator();

final Path src = Paths.get("src\\P7_2\\input.txt");
final Path dst = Paths.get("output.txt");

try (
    final BufferedWriter writer = Files.newBufferedWriter(src, charset, StandardOpenOption.CREATE);
) {
    int lineNumber = 1;
    for (final String line: Files.readAllLines(src, charset))
        writer.write(String.format("/* %d */ %s%s", lineNumber++, line, lineSeparator));
    writer.flush();
}

Upvotes: 1

Braj
Braj

Reputation: 46841

Use

out.println("/* " + i + "*/" + lines.get(i));

in place of

out.println("/* " + i + "*/" + lines);

You are printing complete list in each line.

Upvotes: 0

Related Questions