Reading a text file & adding the content to an ArrayList

久未见 提交于 2019-12-08 13:46:52

问题


I am learning about all of the different ways to take input from a text file and read through the content. I am struggling to use a try - catch block (with resources), and reading in the file name.

Below is what I have written for this part so far:-

public static void main(String[] args) 
{

    ArrayList<StationRecord> data = new ArrayList<>();
    String stationName = null;

    Scanner scan = new Scanner(System.in);
    System.out.println("What is the filename?");
    String input = scan.nextLine();
    File file = new File(input);

    try(BufferedReader in = new BufferedReader(new FileReader(file))){

      while(scan.hasNext()){

       stationName = scan.nextLine();
       int yearMonthDay = scan.nextInt();
       int max = scan.nextInt();
       int min = scan.nextInt();
       int avg = scan.nextInt();
       double dif = scan.nextDouble();

       StationRecord sr = new StationRecord(yearMonthDay, max, min, avg, dif);
       data.add(sr);
      }

    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    catch(Exception e)
    {
        e.printStackTrace();

    }
}

I am trying to do this for not only one file, but two of them. Regardless, here is a sample of input:-

Console: What is the filename?

TempData2018a.txt

After this is entered, I am trying to go through the data in the text file and add it to the ArrayList of type StationRecord (my other class).

Any suggestions and guidance would be much appreciated! Also any input on how you might do this with 2 files would be awesome!.

Edit: .txt file data example

PITTSBURGH ALLEGHENY CO AIRPORT PA
20180101 11 2 7 -22.614762
20180102 12 5 9 -20.514762
20180103 23 2 13 -16.414762

I am trying to store that whole first line in a variable called stationName. Then Im trying to store the next int, int, int, int double in an ArrayList of StationRecord type.


回答1:


Using Java 7 & Java 8 API's feature, you can solve your problem like below:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class LineOperation {

private static List<String> lines;

public static void main(String[] args) throws IOException {

    lines = Collections.emptyList();

    try {
          lines = Files.readAllLines(Paths.get("C:\\Users\\Abhinav\\Downloads\\TempData2018a.txt"), StandardCharsets.UTF_8);

          String stationName = lines.get(0);

          String[] arr = null;

          ArrayList<StationRecord> data = new ArrayList<>();

          for(int i=1;i<lines.size();i++) {

              arr = lines.get(i).split(" ");

              data.add(new StationRecord(Long.parseLong(arr[0]), Integer.parseInt(arr[1]), Integer.parseInt(arr[2]), Integer.parseInt(arr[3]), Double.parseDouble(arr[4])));
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
}
}

But I strongly recommend you to refer below links for your further clarifications on Java I/O:-

  1. Java – Read from File

  2. Read a File into an ArrayList




回答2:


Since this is 2018, please stop using new File(..) and start using nio APIs. As you are using Java 8, you can easily achieve what you are trying to achieve here! So, you can create your StationRecord like this:

Path filePath = Paths.get(pathToFile);

       String stationName =  Files.lines(filePath)
            .findFirst()
            .get();

        List<StationRecord> stationRecords =
            Files.lines(filePath)
                .skip(1) //Skip first line since it has station name
                .map(line -> line.split("\\s")) // split at a space starting from 2nd line
                .map(
                stationData -> new StationRecord(Integer.valueOf(stationData[0]),
                    Integer.valueOf(stationData[1]), Integer.valueOf(stationData[2]),
                    Integer.valueOf(stationData[3]), Double.valueOf(stationData[4]))) // Create StationRecord object using the split fields
                .collect(Collectors.toList()); // Collect result to an ArrayList


来源:https://stackoverflow.com/questions/53217833/reading-a-text-file-adding-the-content-to-an-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!