0

so I am trying to read and split the following data up into an array. However, the txt file only has one line.

1, 5, 3, 7, 9, 5, 3, 1, 9, 5, 7, 3, 7, 5, 9, 1, 3, 5

And I am not sure if I am correctly doing it with my code.

 try { 
      File cars = new File("cars.txt");
      Scanner myReader = new Scanner(cars);
      String data = myReader.nextLine();
      while (myReader.hasNextLine()) {
        data = myReader.nextLine();
        String values[] = data.split(",");
        System.out.print(values);
      }
Aman
  • 11
  • 3
  • 2
    The Scanner class has a [`useDelimiter`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#useDelimiter-java.lang.String-) method that seems like it would be useful, here. – ant Oct 06 '21 at 20:57
  • try with `BufferedReader` and this answers your question https://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java – Maneesha Indrachapa Oct 06 '21 at 20:57
  • My recommendation: hook up a List instead of Array and every time you read in another line, you send that line into a method that splits it into numbers and add all those to the existing List. At the end of the day you'll get a full list of all the numbers. And if you only have one line so what? – Janos Vinceller Oct 06 '21 at 21:03
  • 1
    The line "String data = myReader.nextLine();" reads the line, which means that on the next line, "myReader.hasNextLine()" will return false and the contents of your while loop never runs. Either change the former line to "String data;" or instantiate the String inside the loop. – bschellekens Oct 06 '21 at 21:16
  • Do what bschellekens says and also instead of `System.out.print(values);` do `System.out.print(Arrays.toString(values));` – k314159 Oct 06 '21 at 21:46

3 Answers3

1

How to read in values from a single line in a txt file

I would do it like this.

  • [\\s+,]+ - use a delimiter of any mix of whitespace and commas (including multiple commas).
try (Scanner myReader = new Scanner(new File("f:/cars.txt"))) {
     myReader.useDelimiter(Pattern.compile("[\\s+,]+"));
     while (myReader.hasNextInt()) {
       System.out.println(myReader.nextInt());
     }
} catch (IOException ioe) {
     ioe.printStackTrace();
}


  
WJS
  • 36,363
  • 4
  • 24
  • 39
0

I'd do it something like this without too much error handling or complex stuff. This is tested with a one line cars.txt and a more than one line cars.txt. Have fun with it!

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String args[]) throws Exception {

        File cars = new File("cars.txt");
        List<Integer> numbers = new ArrayList<>();

        Scanner myReader = new Scanner(cars);

        while (myReader.hasNextLine()) {
            processLine(myReader.nextLine(), numbers);
        }

        myReader.close();

        System.out.println(Arrays.deepToString(numbers.toArray()));
    }

    private static void processLine(String oneline, List<Integer> numbers) {
        String values[] = oneline.split(",");
        Arrays.stream(values).forEach((value) -> numbers.add(Integer.parseInt(value.trim())));
    }
}

Or maybe for beginners this would be better to look at:

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String args[]) throws Exception {
        File cars = new File("cars.txt");
        List<Integer> numbers = new ArrayList<>();

        Scanner myReader = new Scanner(cars);

        while (myReader.hasNextLine()) {
            processLine(myReader.nextLine(), numbers);
        }

        myReader.close();

        System.out.println(Arrays.deepToString(numbers.toArray()));
    }

    private static void processLine(String oneline, List<Integer> numbers) {
        String numbersAsStrings[] = oneline.split(",");
        for (int loopIndex = 0; loopIndex < numbersAsStrings.length; loopIndex++) {
            String oneNumberAsString = numbersAsStrings[loopIndex].trim();
            Integer oneNumber = Integer.parseInt(oneNumberAsString);
            numbers.add(oneNumber);
        }
    }
}
Janos Vinceller
  • 1,208
  • 11
  • 25
0

Another example. BufferedReader, try-with-resources, and stream.

    File file = new File("src/defaultpackage/cars.txt");

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

        String line = null;

        while ((line = br.readLine()) != null) {

            String[] arr = line.split(",");

            for (int i = 0; i < arr.length; i++) {

                System.out.println(arr[i]);

            }

        }

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

    System.out.println("end of file");
etoygar
  • 57
  • 4
  • You're not making much use of Streams. You're taking an array, converting it to a stream, and converting that back to an array again. Not much point in that. – k314159 Oct 06 '21 at 22:23
  • You're right, thanks. There's no need. Edited. – etoygar Oct 07 '21 at 10:49