-1

I have the following code, where I'm counting the lines in a file. And I also want to retrieve the very last line (which is integer) :

try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;


       boolean empty = true;
       while ( (readChars = is.read(c)) != -1) {


            for (int i = 0; i < readChars; ++i){
                if (c[i] == '\n'){
                    ++count;
                    empty = true;
                    lastLine = c[i].intValue();
                } else {
                    empty  = false;
                }
            }
       }
       if (!empty) {
        count++;
       }
       System.out.println("the last line was "  + lastLine);
    return count;

I added this line - lastLine = c[i].intValue(); But this gives the error :

C:\Java_Scratch>javac ParentClass2.java ParentClass2.java:90: byte cannot be dereferenced lastLine = c[i].intValue();

How do I convert the byte to int ?

Caffeinated
  • 11,982
  • 40
  • 122
  • 216

1 Answers1

1

The reason your error is being thown in because the last byteyou are trying to convert to an integer is not that last integer from the file you want, but the '\n' at the end of the file.

To get the last line you could loop through the file as you do, but create a variable to keep track of the last line. Here's an example derived from this solution:

String currentLine = "", lastLine = "";

while ((currentLine = in.readLine()) != null) 
{
    lastLine = currentLine;
    // Do whatever you need to do what the bytes in here
    // You could use lastLine.getBytes() to get the bytes in the string if you need it
}

Note: the 'in' in this case is a BufferedReader, but you could use any other file reader as well.


To extract a number from the last line, use the following:

int lastLineValue = Integer.parseInt(lastLine);

Note: Integer.parseInt(x) takes in any String as a parameter and returns the contained integer


You also asked how to convert a byte to an int. There are two methods:

  1. Preferred: Simply set the int equal to the byte, as follows:

    int x = c[i];

This works because this is not an upcast, just like how double d = 5; works perfectly as well.

  1. Or if you need any other Byte methods for whatever reason, you could create a Byte object with the current primitive byte, as follows:

    Byte b = c[i]; int x = b.intValue();

Community
  • 1
  • 1
Bimde
  • 722
  • 8
  • 20