简体   繁体   中英

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()); with this and debug the code but when the first cycle is do the while condition (sc.hasNext()) return false . but in the file there is 2 line.

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*"

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