duca
duca

Reputation: 153

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 :

^^:::[email protected]:::[email protected]:::grbvfcsx:::yrdfsx:::Wed_Sep_05_09:25:51_CEST_2018:::-1568000361:::^^
  ^^:::[email protected]:::[email protected]:::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

Upvotes: 0

Views: 561

Answers (1)

kumesana
kumesana

Reputation: 2490

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

Upvotes: 2

Related Questions