0

find a String inside of the text file. Then getting the following line and need to Split

my code write here

   import java.util.*; // for Scanner 
                import java.io.*; // for File and IOException 

                public class FileReadTest {

                    public static void main(String[] args) throws IOException {
            File f = new File("a.dat");
             Scanner fin = new Scanner(f);
        String airportcode = "HOI";
            while (fin.hasNextLine()) {

                            String line = fin.nextLine();
                            //System.out.println(filename);
                            if (line.contains(airportcode)) {

                                System.out.println(line); //1 sout


                         String[] split = line.split("|");
                        for (int i = 0; i < split.length; i++) {
                            String split1 = split[i];
                            System.out.println(split1);
                        }
                                break;
                            } 
}
            }}

the 1 sout look like this French Polynesia|HOI|Hao|Tuamotos|Hao Airport

So after I'm trying to split by this "|" but it's output look like this

French Polynesia|HOI|Hao|Tuamotos|Hao Airport
F
r
e
n
c
h

P
o
l
y
n
e
s
i
a
|
H
O
I
|
H
a
o
|
T
u
a
m
o
t
o
s
|
H
a
o

A
i
r
p
o
r
t
BUILD SUCCESSFUL (total time: 5 seconds)

but i need like this

French Polynesia
HOI
Hao
Tuamotos
Hao Airport

What Should I do?

2 Answers2

2

The problem is that the split method takes a regular expression as argument, you need to escape the pipe char to actually split on | and get the right result

String[] split = line.split(Pattern.quote("|"));

or

String[] split = line.split("\\|");
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
1

Split it using \\|

Demo:

public class Main {
    public static void main(String[] args) {
        String line = "French Polynesia|HOI|Hao|Tuamotos|Hao Airport";
        String[] split = line.split("\\|");
        for (int i = 0; i < split.length; i++) {
            System.out.println(split[i]);
        }
    }
}

Output:

French Polynesia
HOI
Hao
Tuamotos
Hao Airport
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110