[英]Java - Adding sections of a txt file to an array
我导入了一个.csv
数据库文件,其中列出了程序的用户以及表单中的其他信息:UserName,Password,PropertyName,EstimatedValue。
我已经想到了如何获取用户名,但它只会读取数据库中的最后一个用户名而不是其他用户名。 非常感谢帮助。
import java.util.*;
import java.io.*;
public class readCSV
{
String[] userData;
public void checkLogin() throws IOException
{
try
{
File file = new File("C:/Users/Sean/Documents/Programming assigment/Users.csv");
BufferedReader bufRdr = new BufferedReader(new FileReader(file));
String lineRead = bufRdr.readLine();
while(lineRead != null)
{
this.userData = lineRead.split(",");
lineRead = bufRdr.readLine();
}
bufRdr.close();
}
catch(Exception er){
System.out.print(er);
System.exit(0);
}
}
}
违规行是这样的:
this.userData = lineRead.split(",");
你应该将它放入一些集合中,例如列表
final List<String[]> userData = new LinkedList<String[]> ();
try
{
File file = new File("C:/Users/Sean/Documents/Programming assigment/Users.csv");
BufferedReader bufRdr = new BufferedReader(new FileReader(file));
String lineRead = bufRdr.readLine();
while(lineRead != null)
{
this.userData.add (lineRead.split(","));
}
bufRdr.close();
}
catch(Exception er){
System.out.print(er);
System.exit(0);
}
你的路线;
this.userData = lineRead.split(",");
每次迭代this.userData
覆盖this.userData
的值,结果就是它只保存最后一次迭代的值。
您的String [](userData)在每次迭代时都被替换/覆盖,您必须将它们存储在数组/集合中。
List<String[]> list = new ArrayList<String[]>();
while((lineRead=bufRdr.readLine())!= null)
{
this.userData = lineRead.split(",");
list.add(this.userData);
}
bufRdr.close();
要打印内容:
for(String[] str : list){
for(String s: str){
System.out.pritnln(s);
}
}
如果你想阅读许多用户,你需要一个userdata的ArrayList:
其中this.userData定义为
ArrayList<UserData> userDataList;
在你的循环中:
while(lineRead != null)
{
this.userDataList.add(lineRead.split(","));
lineRead = bufRdr.readLine();
}
您当前的代码循环遍历所有名称,但会覆盖每次迭代中的值。 最后只保留最后一个值。
问题是在你的while循环中你将字符串分配给同一个变量......所以一旦你读完了整个文件......变量只保存最后一个值。
你需要做的是:
Vector<String> userData = new Vector<String>();
然后在你的循环中......
userData.add(lineRead);
然后你可以拆分每一个并在那时做额外的处理....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.