简体   繁体   中英

how to identify the special character in data file in java while reading in java?

how to identify the special character in data file in java while reading in java ?

Example: in below text file at line 5 after test5 having the enter character. ho can we know in java while reading the file.

12,test1,test2,test3,test4
13,test2,test2,test3,test4
14,test3,test2,test3,test4
15,test4,test2,test3,test4
16,test5
,test6,test7,test8
17,test4,test2,test3,test4

You can do this using BufferedReader.read() . It reads the file character by character. So, we can check each character to see whether it is a "carriage return" (13), "new line" (10) etc.

In Windows, line break is normally "carriage return" + "new line".

(The file "data.txt" has the text you have mentioned in the question.)

import java.io.*;

public class ReadCharacters
{
  public static void main(String[] args) throws IOException
  {
    BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
    int i;
    int previousI = -1;
    while ((i = reader.read()) != -1)
    {
      if (i == 13)
      {
        System.out.println("Carriage return (\\r) character");
      }
      else if (i == 10)
      {
        System.out.println("New line (\\n) character");
        if (previousI == 13)
        {
          System.out.println("LINE BREAK (\\r\\n) FOUND!\n");
        }
      }
      else
      {
        System.out.println((char) i);
      }
      previousI = i;
    }
  }
}

Output is:

1
2
,
t
e
s
t
1
,
t
e
s
t
2
,
t
e
s
t
3
,
t
e
s
t
4
Carriage return (\r) character
New line (\n) character
LINE BREAK (\r\n) FOUND!

1
3
,
t
e
s
t
2
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM