如何获取我的CountLines函数(在Java中),输出文件中的最后一个数字?

时间:2015-12-01 01:47:32

标签: java io

我有以下功能,它计算一个简单文件中的行。这个文件由换行符分隔的整数组成,但问题是它一次只能出现一个字符。因此,如果最后一行有2位数,它只会返回第二位数作为最终输出:

这是我的代码:

public static int countLines(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));


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

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

         //System.out.println (" The array is + readChars " + readChars + " !!!" );

            for (int i = 0; i < readChars; ++i){
                Byte b  = c[i];
                int xx = b.intValue();
                lastLine =  xx; 

                if (c[i] == '\n'){
                    ++count;
                    empty = true;

                } else {

                    empty  = false;
                }      
            }   // END inner- FOR-LOOP  

       }// END WHILE-LOOP
        if (!empty) {
        count++;
       }


   int asciiVal  = lastLine;
   int lastLine2 = Character.getNumericValue(asciiVal);
   System.out.println("the last line was "  + lastLine2);

   return count;


    } finally {
        is.close();
    }

}//END method countLines

以下是它正在阅读的输入的示例文本文件:

1
2
3
4
5
6
7
8
9
17

任何提示赞赏。我想学习更好的Java编码,IO等与此相关的主题。感谢

2 个答案:

答案 0 :(得分:2)

使用Scanner而不是InputStream读取行并计算/打印出来可以这样做。

Scanner scan = new Scanner(System.in);
// All your stuff up until the while loop
while (scan.hasNext()) {
     if (sc.nextLine().equals("")) break;
     System.out.println (" The array is + scan.nextInt() " + readChars + " !!!" );
     count++;
}

以上内容将遍历文本文件中的所有行(仅包含数字)并打印出来并为每行传递的内容添加计数(如果有数字,则包括最后一行)。同样如上所述,不需要布尔值empty

BufferedReader使用的内存略少于Scanner,但Scanner更容易使用。我没有使用InputStream作为输入扫描方法的经验。

编辑 :这是一个BufferedReader示例,因为我很无聊。您将需要添加throws声明或使用try-catch(显示)才能使用BufferedReader

    BufferedReader buff = new BufferedReader (new InputStreamReader(System.in));
    // All your stuff up until the while loop
    try {
        String read = buff.readLine();
        while (read.equals("") == false && read.equals("\n") == false) {

            int nextInt = Integer.parseInt(read);
            System.out.println (" The array is + scan.nextInt() " + nextInt + " !!!" );
             count++;
            read = buff.readLine();

        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

正如您所看到的,BufferedReader需要的代码要多得多,但实际上只是偏好。

获取文件中的最后一行只需要稍作修改即可。您只需跟踪每个int,然后对每个新扫描的int进行扫描,然后再写入前一个{4}。当您用完行时,变量中当前保存的int将是最后一行。

答案 1 :(得分:2)

我准备了最接近你的解决方案(就编辑距离而言)

import java.io.*;

public class Main {

    public static int countLines(String filename) throws IOException {
        InputStream is = new BufferedInputStream(new FileInputStream(filename));


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

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

                for (int i = 0; i < readChars; ++i){
                    Byte b  = c[i];
                    lastLine = b.intValue() - 48;

                    if (empty) {
                        lastNumber = 0;
                    }

                    if (c[i] == '\n'){
                        ++count;
                        empty = true;

                    } else {
                        lastNumber *= 10;
                        lastNumber += lastLine;
                        empty  = false;
                    }
                }   // END inner- FOR-LOOP

            }// END WHILE-LOOP
            if (!empty) {
                count++;
            }


            int asciiVal  = lastLine;
            int lastLine2 = Character.getNumericValue(asciiVal);
            System.out.println("the last line was "  + lastNumber);

            return count;


        } finally {
            is.close();
        }

    }//END method countLines

    public static void main(String[] args) throws IOException {
        System.out.print(countLines("/tmp/test.txt"));
    }
}

这里会发生什么:

  • 我正在阅读,因为你做char char
  • 由于c[i]ASCII字节intValue(),因此返回其ASCII值。要获得此特定数字的“实际”值,请使用0的ASCII代码减少它。例如,intValue() '5'的{​​{1}}是53,当我们减去48(intValue() '0')时,我们得到5
  • 因为我们使用decimal system来“添加”右侧的新数字,我们需要将整数乘以10然后再添加该数字
  • 当检测到新行时,lastNumber设置为0

此解决方案不是最好的,也不是防弹。文件不存在或包含字母时会发生什么?可能Scanner是更好的工具。如果你不想学习基础知识,我真的鼓励你去看看CodeWars