简体   繁体   中英

How can I make this Java read the whole last line, and not just each byte at a time?

I have a simple Java IO program which reads from a text file of numbers that looks like this :

1
2
3
4
5
6
7
8
9
17

It's supposed to simply print the lines in this text file to the console, and then tell me what the last line was. But it's printing the last line, here 17 , as just 7 -

Here's my code so far :

import java.lang.*;
import java.io.*;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ParentClass3{
static int lastLine = 0;

public static void main(String[] args) {



    File file = new File("C:\\Java_Scratch_\\someFile.txt");

    try {

        Scanner sc = new Scanner(file);


        while (sc.hasNextLine()) {

        try { 
            int i = sc.nextInt();
            System.out.println(i);
        } catch (Exception e) {
            System.out.println (" here is the stack trace " + e.getStackTrace() );
            System.out.println (" here is the stack trace " );
          }        
        }
        sc.close();


    } // END big-outer-Try


    catch (FileNotFoundException e) {
        e.printStackTrace();
    }


   try  {
    int i = ParentClass3.countLines("C:\\Java_Scratch_\\someFile.txt");
    System.out.println("There are " + i + " lines");
   }
   catch (IOException ioe) {
    System.out.print("ioe" + ioe.getStackTrace() );
   }

 }

// putting the count function


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) {


            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;
                }      
            }

       }
        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


 // end-count_func

}

How would I fix it, so that it says "the last line was 17" , rather just just 7 ?

该method nextLine()应该可以工作,尽管我不记得该输入是否会解析为字符串,但我想这不会影响,但是无论如何...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM