2

我已经导入了一个.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);
        }
    }


}
4

5 回答 5

5

违规行是这样的:

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);
    }
于 2012-11-22T16:26:41.093 回答
2

您的线路;

this.userData = lineRead.split(",");

每次迭代都会覆盖 的值this.userData,结果是它只保存最终迭代的值。

于 2012-11-22T16:27:05.157 回答
1

您的 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);
    }
}
于 2012-11-22T16:26:59.113 回答
1

如果你想读取许多用户,你需要一个用户数据的 ArrayList:
this.userData 定义为

 ArrayList<UserData> userDataList;

在你的循环中:

 while(lineRead != null)
 {
      this.userDataList.add(lineRead.split(","));
      lineRead = bufRdr.readLine();
 }

您当前的代码会遍历所有名称,但会覆盖每次迭代中的值。最后只保留最后一个值。

于 2012-11-22T16:36:51.587 回答
0

问题是在你的while循环中你将你的字符串分配给同一个变量......所以一旦你阅读了整个文件......这个变量只保存最后一个值。

你需要做的是:

Vector<String> userData = new Vector<String>();

然后在你的循环中......

userData.add(lineRead);

然后稍后您可以拆分每个并在那时进行其他处理....

于 2012-11-22T16:28:26.117 回答