0

I've read these two stack overflow posts: this one and this one. I've followed the answers and am still getting no where.

I'm trying to read in a text file (this one) and store it in an ArrayList. But when i go ahead and print the contents of the ArrayList to the console, nothing is returned...

Any help would be appreciated.

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

    ArrayList<Integer> test = new ArrayList<Integer>();

    Scanner textFileOne = new Scanner(new File("ChelseaVector.txt"));

    while (textFileOne.hasNext()) {
        if(textFileOne.hasNextInt()) {
            test.add(textFileOne.nextInt());
        } else {
        textFileOne.next();
        }
    }
    textFileOne.close();

    System.out.println(test);   
}
  • It's probably due to file's structure. Notice, that the contents of `"ChelseaVector.txt"` are enclosed in square brackets (`[]`). Try removing them. – atmostmediocre Jun 24 '18 at 17:54

4 Answers4

0

You need to skip the [ character at the beginning of the file, and define your delimiter as ]:

Scanner textFileOne = 
    new Scanner(new File("ChelseaVector.txt")).useDelimiter(", ").skip("\\[");
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0
List<String> originalFile = new ArrayList<>(Files.readAllLines(Paths.get("ChelseaVector.txt")));
List<Integer> formattedFile = new ArrayList<>();

for (String line : originalFile ) {
    String newLine = line.replaceAll("[", "").replaceAll("]", "").replaceAll(" ", "");
    List<String> numbers = Arrays.asList(String.join(","));
    formattedFile.addAll(numbers);
}

System.out.println(formattedFile);
GJCode
  • 1,959
  • 3
  • 13
  • 30
0

You can do like this

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

        ArrayList<Integer> test = new ArrayList<Integer>();

        Scanner textFileOne = new Scanner(new File("ChelseaVector.txt")).useDelimiter(",");

        while (textFileOne.hasNext()) {
            if (textFileOne.hasNextInt()) {
                test.add(textFileOne.nextInt());
            } else {
                int number=Integer.parseInt(textFileOne.next().replaceAll("[\\[\\]]","").trim());
                test.add(number);
            }
        }
        textFileOne.close();

        System.out.println(test);
    }
Manoj Kumar Dhakad
  • 1,862
  • 1
  • 12
  • 26
0

Since your file contains one line only, you shouldn't be using a loop in my opinion. The following code should work if you're using

String[] strings = Files.lines(Paths.get("ChelseaVector.txt")).findFirst().split("\\D+");
List<Integer> ints = Arrays.stream(strings).map(Integer::valueOf).collect(Collectors.toList());
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89