在文本文件中查找字符串。然后得到以下行,需要分割

问题描述 投票:0回答:3

在文本文件内找到一个字符串。然后得到以下行,需要分割

我的代码写在这里

   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;
                            } 
}
            }}

1出口外观如下French Polynesia|HOI|Hao|Tuamotos|Hao Airport

因此,在我尝试按此"|"分割后,它的输出看起来像这样

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)

但是我需要这样

French Polynesia
HOI
Hao
Tuamotos
Hao Airport

我该怎么办?

java swing java.util.scanner java-io
3个回答
1
投票

|是正则表达式中的元字符。您需要对其进行转义:

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

整个类看起来像这样:

`导入java.util。; //对于扫描仪导入java.io。; //用于File和IOException

公共类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.print(line); // 1 sout

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

}`

做让你感动的事情!


1
投票

使用\\|分割

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]);
        }
    }
}

输出:

French Polynesia
HOI
Hao
Tuamotos
Hao Airport

1
投票

问题是,split方法采用正则表达式作为参数,您需要转义管道字符以在|上实际分割并获得正确的结果

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

String[] split = line.split("\\|");
© www.soinside.com 2019 - 2024. All rights reserved.