【发布时间】:2019-09-09 01:54:52
【问题描述】:
我正在尝试读取和打印带有 Java 分隔符的文本文件。当我使用该函数时,它只打印第一个对象。 我使用 Apache NetBeans 11.1。这是我的代码:
public void Show() throws FileNotFoundException, IOException{
FileInputStream fstream=new FileInputStream("usuarios.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String aux;
String total = "";
String name="" , addres="";
String id = "";
int information=0;
try{
while((aux=br.readLine())!=null){
for(int i=0;i<aux.length(); i++){
if(aux.charAt(i)!='&'){
total+=aux.charAt(i);
}else{
information++;
switch(information){
case 1:{
id=total;
break;
}
case 2:{
name=total;
break;
}
case 3:{
addres=total;
break;
}
}
total="";
}
}
System.out.println("Id: " + id + " Name: " + name + " Address: " + addres);
}
}catch(IOException ex){
}
}
在文本文件中我有:
1&John&Address #1&
2&Peter&Address #2&
3&Robert&Address #3&
我的输出:
Id: 1 Name: John Address: Address #1
Id: 1 Name: John Address: Address #1
Id: 1 Name: John Address: Address #1
预期输出:
Id: 1 Name: John Address: Address #1
Id: 2 Name: Peter Address: Address #2
Id: 3 Name: Robert Address: Address #3
【问题讨论】:
-
你正在吃异常。您的程序可能会引发错误。尝试在 catch 块中打印错误
-
stackoverflow.com/a/17838196/2956272 问题是你为什么会抓到它?
-
在打开你的while循环后尝试打印
aux,看看你是否真的在阅读文件的每一行
标签: java