1

Please help me with adding number of lines of original file.

Im trying to write lines which met specified conditions from file A to file B. There is no problem, but I need to write number of lines of file A to the end of file B and also add number of lines of file B.

Program runs through file A, if condition is met, line is written to the file B, however I stuck to add number of lines after that.

For the last 2 hours I already tried second BufferedWriter, second "try" block, bw.write(lines) and many more, but nothing worked. System.out.println(lines) worked good, so Im really confused.

Here's my actual code:

try (
    BufferedReader bReader = new BufferedReader(new FileReader("fileA.txt"));
    BufferedWriter bWriter = new BufferedWriter(new FileWriter("fileB.txt"));
    LineNumberReader lineNumberReader = new LineNumberReader(new FileReader("fileA.txt"));
    ){
        lineNumberReader.skip(Long.MAX_VALUE);
        int lines = lineNumberReader.getLineNumber();
        lineNumberReader.close();
        String line;
        while ((line = bReader.readLine()) != null){
            String[] values = line.split(" ");
            int time = Integer.parseInt(values[3]);
            if (time < 16){
                bWriter.write(values[0] + ' ' + values[1] + ' ' + values[2] + "\n");
            }
        }
    }
romanzdk
  • 930
  • 11
  • 30

1 Answers1

1

You can do that by adding bWriter.write(""+lines); after while loop.

You have to use bWriter.write(string) instead of bWriter.write(int).

bWriter.write(string) - the string value is written to the file as is.

bWriter.write(int); - It won't work because the int passed is converted to corresponding char and is then written to the file. The char corresponding to your lines value must be some non-printable character, and hence you are not able to see it.

Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86