简体   繁体   English

Java扫描程序仅读取文件的第一行

[英]Java scanner read only the first line of a file

I wrote this code cause I need to read some line of a file to get the data and put them in a object. 我写这段代码是因为我需要读取文件的某些行以获取数据并将其放入对象中。 The trouble is that the scanner read only the first line . 问题在于扫描仪只能读取第一行。 I try to do the print System.out.println(sc.hasNext()); 我尝试做打印System.out.println(sc.hasNext()); with this and debug the code but when the first cycle is do the while condition (sc.hasNext()) return false . 这样做并调试代码,但是在执行第一个循环时,while条件(sc.hasNext())返回false。 but in the file there is 2 line. 但是文件中有2行。

Scanner sc =null;
    int[] counter=new int[users.length];


    for(int i=0;i<users.length-1;i++){
        sc= new Scanner(new FileReader("src/MailListUser"+String.valueOf(i+1)+".txt")).useDelimiter("\\s*^^\\s*");
        while(sc.hasNext()){
            String mail =sc.next();
            String [] data= mail.split(":::");
            Email email;
            String dat=data[5].replaceAll("_", " ");
            DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy",Locale.ENGLISH);
            Date date = format.parse(dat);
            email = new Email(data[1],data[2],data[3],data[4],date,Integer.parseInt(data[6]));
            if(i+1==1) {
                counter[i]++;
                mbUser1.add(email);
            }
            else if(i+1==2){
                counter[i]++;
                mbUser2.add(email);
            }
            else if(i+1==3){
                counter[i]++;
                mbUser3.add(email);
            }

        }

    }
    sc.close();

there is the code . 有代码。 the file contain : 该文件包含:

^^:::user1@unito.it:::user1@unito.it:::grbvfcsx:::yrdfsx:::Wed_Sep_05_09:25:51_CEST_2018:::-1568000361:::^^
  ^^:::user1@unito.it:::user1@unito.it:::rgvfcdsx:::trvedcs:::Wed_Sep_05_09:27:53_CEST_2018:::482784668:::^^

every line of this file start with ^^ and end with ^^ 该文件的每一行都以^^开头,以^^结束

I can't understand why this code read only one line 我不明白为什么这段代码只能读一行

In regular expressions, ^ is a special character. 在正则表达式中, ^是一个特殊字符。 It represents start of input, rather than just the character ^ itself. 它代表输入的开始,而不仅仅是字符^本身。

You need to escape it in your pattern: 您需要按照您的模式对其进行转义:

"\\s*\\^\\^\\s*"

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

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