0

Im trying to read from an input file using useDelimiter function. My files include "/ and \r\n" as separator. Naturally, I went for scanner.useDelimiter("/|\r\n") but the output returned is funny, specifically the first character of the file

The code is as below:

Scanner readfile = new Scanner(new File("text.txt")).useDelimiter("/|\r\");          
while(readfile.hasNext()) {                              
    System.out.println(readfile.next());
}

The input file is as below:

Dr A/P0001/N28-201/012-3465789/1
Dr B/P0002/D03-356/013-3334445/3
Dr C/SP0001/K12-311/014-9988655/4
Dr D/SP0002/T09-101/018-8888333/2
Dr E/P0003/L34-213/014-6655241/0

The output returned:

锘緿r A
P0001
N28-201
012-3465789
1
Dr B
P0002
D03-356
013-3334445
3
Dr C
SP0001
K12-311
014-9988655
4
Dr D
SP0002
T09-101
018-8888333
2
Dr E
P0003
L34-213
014-6655241
0

Can somebody help? I've been searching the internet for one whole week. Thanks in advance.

Tyson Reese
  • 53
  • 1
  • 6
  • 2
    Possible duplicate of [Java read file got a leading BOM \[  \]](https://stackoverflow.com/questions/6290261/java-read-file-got-a-leading-bom-%c3%af) – talex May 09 '19 at 06:38
  • Try manually recreating the input file as it may contain hidden characters. – Jaybird May 09 '19 at 06:38
  • @Jaybird Thanks mate, recreating the file did solve the problem. Out of curiosity, how did this happen though? I don't remember typing weird stuff in the file. – Tyson Reese May 09 '19 at 06:50
  • I'm not sure. It could occur when copying data from a website that has a weird / different text encoding for example. – Jaybird May 09 '19 at 06:58
  • The first byte was probably the byte order mark (BOM) inserted by the editor you used. The question linked by talex may have more details about that. – Daniel Junglas May 09 '19 at 07:14

1 Answers1

0

Try changing your code and use BufferedReader.

   public static void main(String[] args)  {
      try {
         BufferedReader in = new BufferedReader(new FileReader("c:\\filename"));
         String str;

         while ((str = in.readLine()) != null) {
            System.out.println(str);
         }
         System.out.println(str);
      } catch (IOException e) {
      }
   }
Martin Mbae
  • 1,108
  • 1
  • 16
  • 27