I am not an experienced Java programmer and i’m trying to write some text to a file and then read it with Scanner. I know there are lots of ways of doing this, but i want to write records to file with delimiters, then read the pieces.
The problem is so small. When I look the output some printing isn’t seen(shown in below). I mean the bold line in the Output that is only written “Scanner“. I would be appreciated if anyone can answer why “String: ” isn’t seen there. (Please answer just what i ask)
I couldn’t understand if it is a simple printing problem or a line end problem with “\r\n”.
Here is the code:
import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner;public class Tmp { public static void main(String args[]) throws IOException { int i; boolean b; String str; FileWriter fout = new FileWriter("test.txt"); fout.write("Testing|10|true|two|false\r\n"); fout.write("Scanner|12|one|true|"); fout.close(); FileReader fin = new FileReader("Test.txt"); Scanner src = new Scanner(fin).useDelimiter("[|\\*]"); while (src.hasNext()) { if (src.hasNextInt()) { i = src.nextInt(); System.out.println("int: " + i); } else if (src.hasNextBoolean()) { b = src.nextBoolean(); System.out.println("boolean: " + b); } else { str = src.next(); System.out.println("String: " + str); } } fin.close(); } }Here is the output:
String: Testing int: 10 boolean: true String: two String: false Scanner int: 12 String: one boolean: true
The problem is that you are writing out the String “String: ” and then writing out control character \r, or carriage return, and then writing out the contents.
The following version should work a bit better for you:
To really see what I am talking about with the \r, you should change your original program so the print code looks like this:
You should see the output: