Mark Miller
Mark Miller

Reputation: 65

Splitting words from a text file

after,before,20 

yes,no,9

so i have those words above on a text file and i want to split them to different parts such that i'll get the result:

after

before

20

and here is my code

File files = new File("yes.txt");
Scanner in = new Scanner(files).useDelimiter("\\,"); 

String x = in.next(); 
String y = in.next(); 
String z = in.next(); 

System.out.println(x); 
System.out.println(y); 
System.out.println(z); 

but the result that comes out is:

after

before

20

yes

what should i do to remove the "yes"??

Upvotes: 2

Views: 2442

Answers (2)

Gergely Králik
Gergely Králik

Reputation: 441

add one more delimiter, use " \\\n " to filter the newlines

Upvotes: 6

Vivin Paliath
Vivin Paliath

Reputation: 95518

You will need to add the \n as a delimeter so that it recognizes newlines. Right now it only recognizes , as a delimeter:

Scanner in = new Scanner(files).useDelimiter(Pattern.compile("[,\\n]"));

Upvotes: 2

Related Questions