具有多个分隔符JAVA的文本文件读取错误

时间:2017-11-06 02:00:15

标签: java object text-files stringtokenizer

Cars.txt

这是我想要在控制台上阅读和显示的文本文件。以下是我阅读文件的代码:

 public class CarMain
 {
public static void main (String args[]) throws IOException
{
    try
    {
        File f = new File("Cars.txt");
        FileReader fr = new FileReader(f);
        BufferedReader br  = new BufferedReader(fr);
        String line = "", fullName;
        String[] arrName = null;
        Car[] c = new Car[3];
        String name, ic, manufacturer, model;
        int num = 0;

        while ((line = br.readLine()) != null) 
        {                      
            StringTokenizer st = new StringTokenizer(line);
            name = st.nextToken();  

            StringTokenizer st2 = new StringTokenizer(line,"://;");
            ic = st2.nextToken();
            manufacturer = st2.nextToken();
            model = st2.nextToken();


            c[num] = new Car(name,ic, manufacturer, model);

            num++;

        }
        br.close();
        fr.close();

        for (int i = 0; i < c.length; i++)
        {
            System.out.println(c[i].toString());
        }
    }
    catch(IOException e)
    {
        JOptionPane.showMessageDialog(null,"error opening file");
    }
   }
}

然后我得到了这个输出:

enter image description here

似乎在&#34 ;;&#34;之后它没有显示模型名称。并且数据不在正确的位置。

我的预期输出是这样的:

 Name: Fatimah Zahra Ali
 IC: 860802105012
 Manufacturer: Proton
 Model: Perdana
        .
        .
        .

请帮忙。谢谢。

2 个答案:

答案 0 :(得分:1)

您的st2是一个新的标记器。您应该从st2读取令牌,如下所示:

 StringTokenizer st2 = new StringTokenizer(line,"://;");
 name = st2.nextToken(); // first token
 ic = st2.nextToken();   // second 
 manufacturer = st2.nextToken(); // third 
 model = st2.nextToken(); // fourth

不需要第一个标记器。

答案 1 :(得分:0)

enter image description here

我把所有的st2都放了,但名字不见了。