好吧……我有这个.txt文件(UTF-8)
4661,SOMETHING,3858884120607,24,24.09 4659,SOMETHING1,3858884120621,15.95 4660,SOMETHING2,3858884120614,19.58
而这段代码
FileInputStream fis = new FileInputStream(new File(someTextFile.txt)); InputStreamReader isr = new InputStreamReader(fis,"UTF-8"); BufferedReader in = new BufferedReader(isr); int i = 0; String line; while((line = in.readLine()) != null) { Pattern p = Pattern.compile(","); String[] article = p.split(line); // I don't know why but when a first line starts with // an integer - article[0] (which in .txt file is 4661) // becomes someWeirdCharacter4661 so I need to trim it // *weird character is like |=>| if (i == 0) { StringBuffer articleCode = new StringBuffer(article[0]); articleCode.deleteCharAt(0); article[0] = articleCode.toString(); } SomeArticle**.addOrChange(mContext,Integer.parseInt(article[0]),article[1],article[2],Integer.parseInt(article[3]),Double.parseDouble(article[4])); i++; }
在模拟器上它很好但在真实设备(HTC Desire)上我得到这个(奇怪的)错误:
E/AndroidRuntime(16422): java.lang.NumberFormatException: unable to parse '4661' as integer
有什么问题?
**它只是我的类需要那些参数作为输入(context,int,string,double)
解决方法
它可能是你的文件不是UTF8或沿着那些行.
但是,如果你想破解修复,因为你只是一个解决方案对问题不感兴趣:)然后删除任何不是数字或小数点的东西.
String[] article = p.split(line); Integer i = Integer.parseInt(article[0].replaceAll("[^0-9.]",""));
正则表达式并不完美(例如,它会影响…… 999 ….)但它会为你做.
编辑:
我似乎没有正确地阅读这个问题.如果只是在文件的开头那么你很可能是一个字节顺序标记,它用于告诉你文件是unicode还是UTF16 / 32,无论是小端还是大端端.你不需要经常看到它被使用.