在文本文件中查找字符串。然后得到以下行,需要按索引和子字符串拆分

Find string inside of the text file. Then getting the following line and need to Split by Index of and substring

在文本文件中查找字符串。然后获取以下行并按 indexOf()substring().

拆分
import java.util.*; 
import java.io.*;

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();
            int firstindex = line.indexOf(airportcode);

            if (firstindex > 0) {
                int Code = line.indexOf("|");
                int Country = line.lastIndexOf("|",Code);
                int State = line.indexOf("|", Country);
                int City = line.indexOf("|", State);
                int Airport = line.indexOf("|", City);
                System.out.println(Code);
                System.out.println(Country);
                System.out.println(State);
                System.out.println(City);
                System.out.println(Airport);
                System.out.println(line.substring(0, Code));
                break;
            }
        }

        fin.close();
    }
}

1 sout 看起来像这样: French Polynesia|HOI|Hao|Tuamotos|Hao Airport 我只需要使用 indexOf()substring(), 但我需要这样:

French Polynesia
HOI
Hao
Tuamotos
Hao Airport

我该怎么办?

假设:

  • 文件内容包含具有以下结构的行:French Polynesia|HOI|Hao|Tuamotos|Hao Airport
  • 你只需要打印那些包含 "HOI" 字符串的行
  • 您只能使用 indexOfsubstring

这是适合您的代码片段(文件 a.dat 位于 resources 文件夹中):

package example;

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(
            Objects.requireNonNull(FileReadTest.class.getClassLoader().getResource("a.dat")).getFile()
        );
        Scanner fin = new Scanner(f);
        String airportcode = "HOI";
        while (fin.hasNextLine()) {
            String line = fin.nextLine();
            if (line.indexOf(airportcode) != -1) {
                int firstindex;
                while ((firstindex = line.indexOf("|")) != -1) {
                    System.out.println(line.substring(0, firstindex));
                    line = line.substring(firstindex + 1);
                }
                System.out.println(line); // last data 
            }
        }
    }
}

假设你总是有相同数量的字段,在你的情况下 5 由字符 | 分隔你可以解决问题而不使用 String split 方法但只使用 indexOf substring 如下所示:

String s = "French Polynesia|HOI|Hao|Tuamotos|Hao Airport";
for (int i = 0; i < 4; ++i) {
    int endIndex = s.indexOf("|");
    System.out.println(s.substring(0, endIndex));
    s = s.substring(endIndex + 1);
}
System.out.println(s);

该代码将打印可分配给不同变量的所有字段。