简体   繁体   English

带有多个定界符JAVA的文本文件读取错误

[英]Text File Reading Error with multiple delimiter JAVA

Cars.txt

This is the text file I want to read and display on console. 这是我要阅读并在控制台上显示的文本文件。 Here are my codes for reading the file: 这是我读取文件的代码:

 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");
    }
   }
}

then I get this output: 然后我得到以下输出:

在此处输入图片说明

It seems that it doesn't display the model name after ";" 似乎没有在“;”之后显示型号名称。 and the data is not in the right place. 并且数据不在正确的位置。

My expected output is like this: 我的预期输出是这样的:

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

Please help. 请帮忙。 Thank you. 谢谢。

Your st2 is a new tokenizer . 您的st2是一个新的令牌生成器 You should read the tokens from st2 as follows: 您应该按照以下步骤从st2读取令牌:

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

The first tokenizer is not required. 不需要第一个标记器。

在此处输入图片说明

I have put all st2 but the name is missing. 我把所有st2都放了,但是名字不见了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM