Scanner遇上UnmappableCharacterException

上周末的时候,朋友约好去KTV,鉴于我这种不怎么听歌的孩子伤不起啊,灵机一动就把我的酷狗歌单导出来了,XML文件嘛,内容太多,我只想要歌名足已。于是写了一个java去输出歌名。
    岂料我受到了挫伤, scanner. hasNextLine ()一直为false,于是我百思不得姐啊,经过调试发现,Scanner内部有 java.nio.charset.UnmappableCharacterException ,就百度了一下,没找到答案,google访问不了,想起公司的网络是香港的,就远程上去,还好在stackoverflow上找到了答案。O(∩_∩)O~~
  原来用改动下面一行就OK啦,不解释,你懂的,不懂就去stackoverflow。
     Scanner scanner= new  Scanner( new  File(filePath), "UTF-8" );
URL: http://stackoverflow.com/questions/19252321/findwithinhorizon-fails-to-match (这个页面上你可以学到更多) 

Java Code:          
  
  
  1. public void output(String filePath) throws FileNotFoundException{
  2. Scanner scanner=new Scanner(new File(filePath));
  3. String str=null;
  4. while(scanner.hasNextLine()){
  5. str=scanner.nextLine();
  6. if(str.indexOf("FileName")>0){
  7. System.out.println(str.substring(str.indexOf(">")+1, str.lastIndexOf("<")));
  8. }
  9. }
  10. scanner.close();
  11. }
File content:
   
   
  1. <File>
  2. <MediaFileType>0</MediaFileType>
  3. <FileName>周杰伦 - 爱在西元前.mp3</FileName>
  4. <FilePath>D:\music\</FilePath>
  5. <FileSize>5623610</FileSize>
  6. <Duration>234292</Duration>
  7. <Hash>0589341ba15528a4c63e36c49a3c0e45</Hash>
  8. <Lyric>E:\KuGou\Lyric\周杰伦 - 爱在西元前-0589341ba15528a4c63e36c49a3c0e45.krc</Lyric>
  9. <Bitrate>192004</Bitrate>
  10. <MandatoryBitrate>0</MandatoryBitrate>
  11. </File>
Java Code after modify:
   
   
  1. public void output(String filePath) throws FileNotFoundException{
  2. Scanner scanner=new Scanner(new File(filePath),"UTF-8");//Always explicitly pass a charset when working with text
  3. String str=null;
  4. while(scanner.hasNextLine()){
  5. str=scanner.nextLine();
  6. if(str.indexOf("FileName")>0)
  7. System.out.println(str.substring(str.indexOf(">")+1, str.lastIndexOf("<")));
  8. }
  9. //It's better to check IOException when working with Scanner(PS:find UnmappableCharacterException took me more time,finally by debug to found )
  10. IOException ioException = scanner.ioException();
  11. if (ioException != null) {
  12. ioException.printStackTrace();
  13. }
  14. scanner.close();
  15. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值