【问题标题】:In Java , How do I obtain the last number from a file?在 Java 中,如何从文件中获取最后一个数字?
【发布时间】:2015-11-22 03:49:38
【问题描述】:

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

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>javac ParentClass2.java ParentClass2.java:90: 字节 不能取消引用 lastLine = c[i].intValue();

如何将字节转换为 int ?

【问题讨论】:

  • byte 是一个原语,它没有可以在其上执行的“方法”。也许试试(int)c[i];
  • @MadProgrammer - 好的,知道了 - 谢谢!
  • @MadProgrammer - 奇怪的事情 - 这确实编译,但即使最后一行是 27 它告诉我它是 10
  • which is integer 在二进制中并不真正意味着任何东西。您必须以某种方式解释这些字节才能在整数上下文中理解它们。
  • if (c[i] == '\n'){ .. lastLine = (int)c[i];},是什么让您认为lastLine 将不同于\nint 表示形式?

标签: java


【解决方案1】:

你的错误被抛出的原因是你试图转换为整数的最后一个字节不是你想要的文件中的最后一个整数,而是文件末尾的 '\n'强>.

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

注意:本例中的“in”是BufferedReader,但您也可以使用任何其他文件阅读器。


要从最后一行中提取一个数字,请使用以下命令:

int lastLineValue = Integer.parseInt(lastLine);

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


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

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

    int x = c[i];

之所以有效,是因为这不是向上转换,就像 double d = 5; 的完美运作方式一样。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 2019-04-16
    • 2012-03-19
    • 2019-05-20
    • 2018-12-23
    • 2018-06-02
    相关资源
    最近更新 更多