How to store text from a certain column in an arra

2019-03-04 16:15发布

问题:

I would like to store only the first column that is contained in the .txt file.

hello28  23232
hello27  23232
hello25  12321

This is the code I have so far, however at the moment it stores every line in the file; how can I make it so that only the first column is stored (The one which contains the user names of the users)?

public static boolean checkUserExists(String userName){
    String line = "";
    ArrayList <String> userNames = new ArrayList <String>();

    try{
       FileReader fr = new FileReader("investments.txt");
       BufferedReader br = new BufferedReader(fr);

        while((line = br.readLine()) != null) {
            userNames.add(line);
        }
        }

    catch(IOException e){
            System.out.println("File not found!");
    }

    if (userNames.contains(userName)){
        return false;
    }
    else{
        return true;
    }        
}   

回答1:

All you need to do is just to split each line using whitespace as a delimiter and keep the first token, and repeat that for every line:

This can be achieved using the following line of code which uses the split function (see more info here http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String))

line.split("\\s+");

Then, the zero-th (0) element contains the first column, as you wish to do

There you go a fully working class:

import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
class white {
public static void main(String[] args) {

    String line = "";
    String username = "";
    ArrayList <String> userNames = new ArrayList <String>();

    try{
       FileReader fr = new FileReader("investments.txt");
       BufferedReader br = new BufferedReader(fr);

        while((line = br.readLine()) != null) {
            line.split("\\s+");
            userNames.add(line.split("\\s+")[0]);
            System.out.println(line.split("\\s+")[0]);
        }
        }

    catch(IOException e){
            System.out.println("File not found!");
    }       
}   
}

OUTPUT:

hello28
hello27
hello25


回答2:

You can extract the part of the line preceding the first space:

userNames.add(line.substring(0, line.indexOf(' ') ));