岂料我受到了挫伤,scanner.hasNextLine()一直为false,于是我百思不得姐啊,经过调试发现,Scanner内部有java.nio.charset.UnmappableCharacterException,就百度了一下,没找到答案,google访问不了,想起公司的网络是香港的,就远程上去,还好在*上找到了答案。O(∩_∩)O~~
原来用改动下面一行就OK啦,不解释,你懂的,不懂就去*。
Scanner scanner=new Scanner(new File(filePath),"UTF-8");
URL:http://*.com/questions/19252321/findwithinhorizon-fails-to-match (这个页面上你可以学到更多)
Java Code:
public void output(String filePath) throws FileNotFoundException{
Scanner scanner=new Scanner(new File(filePath));
String str=null;
while(scanner.hasNextLine()){
str=scanner.nextLine();
if(str.indexOf("FileName")>0){
System.out.println(str.substring(str.indexOf(">")+1, str.lastIndexOf("<")));
}
}
scanner.close();
}
File content:
<File>
<MediaFileType>0</MediaFileType>
<FileName>周杰伦 - 爱在西元前.mp3</FileName>
<FilePath>D:\music\</FilePath>
<FileSize>5623610</FileSize>
<Duration>234292</Duration>
<Hash>0589341ba15528a4c63e36c49a3c0e45</Hash>
<Lyric>E:\KuGou\Lyric\周杰伦 - 爱在西元前-0589341ba15528a4c63e36c49a3c0e45.krc</Lyric>
<Bitrate>192004</Bitrate>
<MandatoryBitrate>0</MandatoryBitrate>
</File>
Java Code after modify:
public void output(String filePath) throws FileNotFoundException{
Scanner scanner=new Scanner(new File(filePath),"UTF-8");//Always explicitly pass a charset when working with text
String str=null;
while(scanner.hasNextLine()){
str=scanner.nextLine();
if(str.indexOf("FileName")>0)
System.out.println(str.substring(str.indexOf(">")+1, str.lastIndexOf("<")));
}
//It‘s better to check IOException when working with Scanner(PS:find UnmappableCharacterException took me more time,finally by debug to found )
IOException ioException = scanner.ioException();
if (ioException != null) {
ioException.printStackTrace();
}
scanner.close();
}