[英]Java scanner read only the first line of a file
我写这段代码是因为我需要读取文件的某些行以获取数据并将其放入对象中。 问题在于扫描仪只能读取第一行。 我尝试做打印System.out.println(sc.hasNext());
这样做并调试代码,但是在执行第一个循环时,while条件(sc.hasNext())返回false。 但是文件中有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();
有代码。 该文件包含:
^^:::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:::^^
该文件的每一行都以^^开头,以^^结束
我不明白为什么这段代码只能读一行
在正则表达式中, ^
是一个特殊字符。 它代表输入的开始,而不仅仅是字符^
本身。
您需要按照您的模式对其进行转义:
"\\s*\\^\\^\\s*"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.