如何在Java中读取文本文件并存储在String数组中?

时间:2013-10-29 11:39:12

标签: java arrays bufferedreader filereader

我有一个文本文件textfile.txt,其中包含如下数据:

A-abc , A-xyz , B-mno , A-ijk , B-pqr

现在,我必须从此文件中读取并将值存储在两个单独的数组"A""B"中,以便前缀为"A-"的值存储在数组A和值中带有前缀“B-”的数据存储在数组B中。

此外,在存储数据时,需要删除前缀,即"abc"只需存储array A

FileInputStream fstream = new FileInputStream("C:\opt\New_Workspace\Salary.txt"); 
// use DataInputStream to read binary NOT text
// DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null)   {
String[] arrayLine1= strLine.split(" , ");
for(String s:arrayLine1)

String[] arrayLine2 = s.split(": ");
{
if(s.matches("Basic: "))
{
basic = Double.parseDouble(arrayLine[1]);                 
}
else if(s.matches("Perc-D ");
{
percD = Double.parseDouble(arrayLine[3]);                
}
else if(s.matches("Perc-A: "))
{
percA = Double.parseDouble(arrayLine[5]);                 
}

}

2 个答案:

答案 0 :(得分:1)

尝试这样的事情: -

FileInputStream in = new FileInputStream("file.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(in));

    String strLine;
    String[] filearray;
    filearray = new String[10];

    while ((strLine = br.readLine()) != null) {

    for (int j = 0; j < myarray.length; j++){
    filearray[j] = br.readLine();
    }

    }
    in.close();

答案 1 :(得分:0)

这是匆忙写的,所以请原谅任何错误:

String aStore = "";
String bStore = "";
String aFinal[];
String bFinal[];
try{
    Scanner input = new Scanner(new File("file.txt"));
    while(input.hasNextLine()){
        String message = input.nextLine();
        message = message.replace(" ", "");
        String store[] = message.split(",");
        for(int a = 0; a < store.length; a++){
            if((store[a]).contains("A-"){
                String t[] = (store[a]).split("-");
                aStore = aStore + "_" + t[1];
            }
            if((store[a]).contains("B-"){
                String t[] = (store[a]).split("-");
                bStore = bStore + "_" + t[1];
            }
        }
        aFinal = aStore.split("_");
        bFinal = bStore.split("-");
    }
    input.close();
}
catch(Exception e){}