简体   繁体   中英

How to read in 1 specific column of a txt file and store into an Array or ArrayList [Java]

The txt file I need to pull data from. I am only concerned with the STID column as I need to compare their Hamming distances with other inputted STID names in another part of the program

Trial code using a Scanner

I was thinking of using a BufferedReader (Although in my first trial I used a Scanner) and then extracting the data using .add() into an ArrayList but was not sure how to implement this as I am new to programming. Any help would be greatly appreciated

With the nextLine() method of the Scanner object ( https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine() ) you can get each line of your text file.

Getting the STID column is pretty easy as it is the first and always starts at the beginning of the line.

What I would do: just use nextLine() a few times to skip the lines you're not interested in. Once you reached the first line containing the first STID the nextLine() method will give you the whole line. It seems that the STID is always 4 characters long so you could use the substring(0,4) method on the line to get only the 4 characters that you want. Once you have this you can just add this substring to your ArrayList.

I went the BufferedReader route, and came up with this:

import java.util.ArrayList;
import java.util.List;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Mesonet {
  public static void main(String[] args) {

    try {
      List<String> STIDS = new ArrayList<String>();
      BufferedReader reader = new BufferedReader(
                              new FileReader("Mesonet.txt"));
      Pattern p = Pattern.compile("^([A-Z0-9]{4}).*");

      reader.readLine(); // repeat as necessary to skip headers...
      while (reader.ready()) {
        String line = reader.readLine();
        Matcher m = p.matcher(line);
        if (m.matches()) {
          STIDS.add(m.group(1));
        }
      }

      for (String STID : STIDS) {
        System.out.println(STID);
      }
    }
    catch (FileNotFoundException err) {
      System.out.println("Where is the file?");
    }
    catch (IOException err) {
      System.out.println("IO Problem");
    }
  }
}

This will match the very first 4 upper-case letter and digit combinations and put them in the array, which then gets printed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM