M.S
M.S

Reputation: 9

Split and Scanner with multiple delimiters

I am attempting to create a Scanner with a delimiter that will parse through lines from a text file and then create arrays using this information and the split() method. However, I am unable to successfully stop the split() method from applying splitting the next line of the text file.

public class Main {

public static void main(String[] args) throws FileNotFoundException {
fileReader("test.txt");
}

public static void fileReader(String filename) throws FileNotFoundException {
    Scanner in = new Scanner(new File(filename));
    in.useDelimiter(",");
    String[] test = in.next().split(":");
    String[] test2 = in.next().split(":");
    System.out.println(Arrays.toString(test));
    System.out.println("\n" + Arrays.toString(test2));
}

}

test.txt

A:B:C,ONE:TWO:THREE
ALPHA:BETA:CHARLIE,FOUR:FIVE:SIX

Output:

[A, B, C]

[ONE, TWO, THREE
ALPHA, BETA, CHARLIE, FOUR, FIVE, SIX]

Expected Output:

[A, B, C] [ONE, TWO, THREE]

Note, I will eventually add a loop to parse through entire text file, creating Arrays using the other lines.

Upvotes: 0

Views: 258

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79075

Replace

in.useDelimiter(",");

with

in.useDelimiter("[," + System.lineSeparator() + "]");

The regex, [,c] matches one of the characters inside the square bracket. Thus, the split will happen on either , or c where c here refers to the line separator character returned by your operating system. Note that different operating system may return different line separators and therefore it's better to use System.lineSeparator() instead of specifying the line separator characters yourself. If you wish to specify the line separator characters yourself, you can specify [,\n\r] but I strongly recommend you use System.lineSeparator() instead of [\n\r].

Upvotes: 1

linux_user36
linux_user36

Reputation: 213

Well, as far as I can tell, you're setting the delimiter to ",". If you instead want to break at new lines, you should set it to "\n" instead. If you do want to use commas, then you should maybe add those to the end of the line(s).

If, however, your goal is to split the file at both commas and new lines, then you should consider using a Reader and splitting the strings yourself when you encounter one of the two.

public static void fileReader(String filename) throws FileNotFoundException, IOException {
    Reader reader = new FileReader(new File(filename));
    StringBuilder sb = new StringBuilder();
    int c;

    while ((c = reader.read()) > 0) {
        if (c == ',' || c == '\n') {
            String[] s = sb.toString().split(":");
            sb.setLength(0);
            // Do something with the separated strings
        } else sb.append((char) c);
    }

    reader.close();
    // ...
}

Upvotes: 1

Related Questions