这是我想要读取并在控制台上显示的文本文件。这是我读取文件的代码:
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");
}
}
}
然后我得到这个输出:
“;”后面好像不显示型号名称并且数据不在正确的位置。
我的预期输出是这样的:
Name: Fatimah Zahra Ali
IC: 860802105012
Manufacturer: Proton
Model: Perdana
.
.
.
请帮忙。谢谢。
最佳答案
您的 st2
是一个新的分词器。您应该从 st2
读取 token ,如下所示:
StringTokenizer st2 = new StringTokenizer(line,"://;");
name = st2.nextToken(); // first token
ic = st2.nextToken(); // second
manufacturer = st2.nextToken(); // third
model = st2.nextToken(); // fourth
不需要第一个标记器。
关于java - JAVA 读取文本文件时出现多个分隔符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47128702/