簡體   English   中英

Java - 將txt文件的各個部分添加到數組中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM