修剪后如何避免这种格式异常 [英] How can i avoid this format exception despite trim

查看:91
本文介绍了修剪后如何避免这种格式异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:隐藏的字符使我的编辑器混乱。

EDIT : hidden character mess'd with my editor.

我想从文本文件中读取内容并将对象添加到其中。

I want to read from my text file and add objects to an array from it. I'm getting a

NumberFormatException: For input string : "2".  

如果删除文件的第一行,则输入字符串 3会出现格式异常。

If I remove the first line of the file, I get a format exception for input string "3".

我在那里想念什么?

ArrayList<Personne> listp = new ArrayList<Personne>();
try {
    FileReader file = new FileReader(personneFilePath);
    Scanner sc = new Scanner(file);
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        String[] attributes = line.split(",");
        listp.add(new Personne(Integer.parseInt(attributes[0].trim()), attributes[1], attributes[2], Double.parseDouble(attributes[3]), attributes[4], attributes[5], attributes[6]));
    }
    file.close();
} catch (FileNotFoundException e) {
    System.out.println("Erreur 1 : " + e.getMessage());
} catch (IOException e) {
    System.out.println("Erreur 2 : " + e.getMessage());
}

这是我正在读取的文件的内容;

Here is the content of the file i'm reading;

2, Claire, Chazal, 65.0 , rue de Rennes, Laval, 53000
3, Jacques, Dupont, 90.0 , rue des Anges, Paris, 75000
4, Celine, Dia, 66.0 , rue Diderot, Paris, 75000
5, Remy, Cheval, 88.0 , rue du paradis, Nantes, 44000


推荐答案

好像您的文件中包含一些不可打印的字符,这些字符在2附近不是空格,所以 trim()无法删除它。

It loosk like your file contains some unprintable characters near 2 which is not whitespace so trim() can't remove it.

要删除它,可以使用 replaceAll( \\D,)代替 trim()

To remove it you can use replaceAll("\\D","") instead of trim().

更好的首选解决方案是消除此问题的原因,因此请正确设置编辑器/文件格式/编码,并停止在文件中放置这些字符。

Better preferred solution would be removing cause of this problem, so set up your editor/file format/encoding properly and stop placing these characters in your file.

这篇关于修剪后如何避免这种格式异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆