简体   繁体   中英

Reading content from text file into ArrayList using Java

I'm facing a problem with moving content from file to ArrayList. The user selects a line from the file by an index which one he wants to add to ArrayList. I've tried with quick.add(new Pastatas()); But as I see it will add my empty constructor there.

private void myobj() {
    File FILE = new File(filex);
    if (FILE.exists() && FILE.length() > 0) {
        try {
            Scanner SC = new Scanner(FILE);
            for (int i = 0; i < FILE.length(); i++) {
                if (SC.hasNextLine()) {
                    String storage = SC.nextLine();
                    System.out.println("ID: " + i + " " + storage);
                }
            }
            System.out.println("select one.");
            Scanner sc = new Scanner(System.in);
            int userInputas = Integer.parseInt(sc.nextLine());
            for (int j = 0; j < FILE.length(); j++) {
                if (userInputas == j) {
                    quick.add(/*Probably problem here*/)
                }
            }
        } catch (IOException e) {
            System.err.println(e.getMessage() + "error");
        }
    }

Use the newer Path, Paths, Files for such tasks.

    Path path = Paths.get(filex);
    List<String> lines = Files.readAllLines(path);

    System.out.println("Select one.");
    Scanner sc = new Scanner(System.in);
    int lineno = Integer.parseInt(sc.nextLine()); // Maybe 1 based
    int index = lineno - 1; // Zero based index

    if (0 <= index && index < lines.size()) {
        String line = lines.get(index);
        System.out.println("Selected: " + line);
        quick.add(line);
    }

The error in the logic:

FILE (or Path above) is just a possibly not existing moniker/name for a file. The length is the number of bytes, the file size. So for a selection of a text line, one has to do something different, like opening, reading, and finally closing the file. The class Files provides utility functions to do such things as loading all lines.


After reading your comments; maybe something more like:

quick.add(new Pastatas(line));

In fact if the file is not a text file, we would need to know how the file was filled.

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