0

I am writing a method for my java class. it looks like this so far:

String file_name;
String line;

void addLine(file_name, line){
            int line_number;
            try {
                FileWriter writer = new FileWriter(file_name, true);
                PrintWriter out = new PrintWriter(writer);

                out.println(line_number + line);
            }
            catch (IOException e){
                System.out.println(e);
            }
        }

How should I define line_number so it would check how many lines were there in file before I printed out next into it?

2 Answers2

0
          int totalLines = 0;

          BufferedReader br   br = new BufferedReader(new   FileReader("C:\\filename.txt"));
                String  CurrentLine = "";
                while ((CurrentLine = br.readLine()) != null) {
                    ++totalLines
                }

i think you have to actually read the file by using a bufferedreader. and then keep on incrementing the totalLines till it reach the end of the file

Priyamal
  • 2,919
  • 2
  • 25
  • 52
0

You can count them with a function posted here: Number of lines in a file in Java

They tested it with a 150 MB log file and it seems to be fast.

Community
  • 1
  • 1
DavidL
  • 1
  • 1