Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Line appearing when reading from input file, even though \n is Delimited

Tags:

java

io

csv

Hello I have this code:

Scanner input = new Scanner(new File("src/data/input.csv"));
input.useDelimiter(",|\\n");
    
    
System.out.println(input.next());
System.out.println(input.next());
System.out.println(input.next());
System.out.println(input.next());
System.out.println(input.next());
System.out.println(input.next());
System.out.println(input.next());
System.out.println(input.next());
System.out.println(input.next());
System.out.println(input.next());

Input.csv is:

-149.95038,61.13712,"McDonalds-Anchorage,AK","3828 W Dimond Blvd, Anchorage,AK, (907) 248-0597"

-149.93538,61.18167,"McDonalds-Anchorage,AK","4350 Spenard Rd, Anchorage,AK (907) 243-5122"

My expected output is:

-149.95038

61.13712

"McDonalds-Anchorage

AK"

"3828 W Dimond Blvd

Anchorage

AK

(907) 248-0597"

-149.93538

61.18167

Instead I get:

-149.95038

61.13712

"McDonalds-Anchorage

AK"

"3828 W Dimond Blvd

Anchorage

AK

(907) 248-0597"

(blank line)

-149.93538

61.18167

I am not sure why the New Line isn't being skipped. Is there a better way to get values from an input file?

like image 270
73est Avatar asked Jan 25 '26 04:01

73est


1 Answers

This is probably a Carriage Return/Line Feed issue. On Windows (and a few other systems), the line delimiter is \r\n instead of \n.

Replace

input.useDelimiter(",|\\n");

with

input.useDelimiter(",|\\n|\\r|(\\r\\n)");

This will make sure that Carriage Return (\r) is picked up.

However, the best way to read your file is to use a BufferedReader instead of a Scanner (you initialize it in the same way). Then, use readLine() to read your line and line.split(",") to split your line at commas.

like image 119
k_g Avatar answered Jan 27 '26 17:01

k_g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!