在Java中,如何从文件中获取最后一个数字?

时间:2015-11-22 03:49:39

标签: java

我有以下代码,我在计算文件中的行。我还想检索最后一行(整数):

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;

我添加了这一行 - lastLine = c[i].intValue(); 但是这给出了错误:

  

C:\ Java_Scratch&gt; javac ParentClass2.java ParentClass2.java:90:byte   不能被解除引用                       lastLine = c [i] .intValue();

如何将字节转换为int?

1 个答案:

答案 0 :(得分:1)

您的错误被丢失的原因是因为您尝试转换为整数的最后一个字节不是您想要的文件中的最后一个整数,而是&#39; \ n&#39;在文件的末尾

要获取最后一行,您可以循环遍历文件,但创建一个变量以跟踪最后一行。这是一个源自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
}

注意:&#39; in&#39;在这种情况下是BufferedReader,但您也可以使用任何其他文件阅读器。

要从最后一行提取数字,请使用以下内容:

int lastLineValue = Integer.parseInt(lastLine);

注意:Integer.parseInt(x)接受任何String作为参数并返回包含的整数

您还询问了如何将字节转换为int。有两种方法:

  1. 首选:只需将int设置为等于字节,如下所示:

    int x = c[i];

  2. 这是有效的,因为这不是一个向上的,就像double d = 5;如何完美地工作一样。

    1. 或者,如果由于某种原因需要任何其他字节方法,可以使用当前原始字节创建一个Byte对象,如下所示:

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