简体   繁体   English

程序仅读取一行而不是整个文件

[英]Program only reading one line instead of entire file

    public static void main(String ar[]) throws FileNotFoundException{
    scan = new Scanner(new FileReader(new File("files.txt")));
    String nextLine = scan.nextLine();
    String[] fileNames = nextLine.split("\\s+");

    for(int i=0;i<fileNames.length;i++){
        System.out.println(fileNames[i]);
    }


    for(int i=0;i<nextLine.length();i++){
        char c = nextLine.charAt(i);
        boolean isWhiteSpace = isWhiteSpace(c);
        if(isWhiteSpace){
            if(c == ' ')
                System.out.println("white space (blank) at index "+i);
            if(c == '\n')
                System.out.println("white space (line feed) at index "+i);
            if(c == '\r')
                System.out.println("white space (\\r - carriage return) at index "+i);
            if(c == '\t')
                System.out.println("white space (\\t - tab) at index "+i);
        }
    }

} 

I need help in solving this issue. 我需要帮助来解决这个问题。 Apparently my program only recognizes the first line in the file, when it supposed to be reading the whole file for the content. 显然,当我的程序应该读取整个文件的内容时,它只能识别文件的第一行。

What changes do I need to make for that? 我需要为此做哪些更改? thanks. 谢谢。

Well, this is because you are only reading one line from the file: 好吧,这是因为您只从文件中读取一行:

scan = new Scanner(new FileReader(new File("files.txt")));
String nextLine = scan.nextLine();

In order to read the entire file you have to call scan.nextLine() until you reach the end of file. 为了读取整个文件,您必须调用scan.nextLine()直到到达文件末尾。 To check for end of file you can do a while loop and thus go through the whole file: 要检查文件结尾,您可以执行while循环,然后遍历整个文件:

Scanner input = new Scanner(new File("\""+filename+"\""));
while(input.hasNextLine())
{
    String data = input.nextLine();
    //Do what you want with one line which is at each iteration stored in data
}

You only seemed to use String nextLine = scan.nextLine(); 您似乎只使用String nextLine = scan.nextLine(); once! 一旦!

String nextLine = scan.nextLine(); 字符串nextLine = scan.nextLine();

That seems to me to only be accepting one line from your file, using your Scanner "scan". 在我看来,使用扫描仪的“扫描”功能只能接受文件中的一行。 Thus you are only getting one line from the file in question. 因此,您从相关文件中仅获得一行。

You are calling the method nextLine() only once, hence you are able to read only 1 line in your program. 您只调用一次nextLine()方法,因此您只能在程序中读取1行。 You have to add a for loop to keep on reading all line available. 您必须添加一个for循环以继续读取所有可用行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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