【问题标题】:Find string inside of the text file. Then getting the following line and need to Split在文本文件中查找字符串。然后得到以下行并需要拆分
【发布时间】:2020-07-05 08:04:40
【问题描述】:

在文本文件中找到一个字符串。然后得到下面一行,需要Split

我的代码写在这里

   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 sout 看起来像这样 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

我该怎么办?

【问题讨论】:

  • @akuzminykh 我需要这样的法属波利尼西亚 HOI Hao Tuamotos Hao 机场

标签: java swing java.util.scanner java-io


【解决方案1】:

问题在于split 方法将正则表达式作为参数,您需要转义管道字符才能在| 上实际拆分并获得正确的结果

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

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

【讨论】:

    【解决方案2】:

    使用\\|拆分它

    演示:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      • 2011-08-01
      • 1970-01-01
      • 2016-07-21
      • 2018-04-18
      • 2016-03-14
      • 2012-08-10
      相关资源
      最近更新 更多