在文本文件中查找字符串。然后获得以下行,并除以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出口看起来像这样:French Polynesia|HOI|Hao|Tuamotos|Hao Airport
我只需要使用indexOf()
和substring()
,但我需要这样:
French Polynesia
HOI
Hao
Tuamotos
Hao Airport
我该怎么办?
假设:
French Polynesia|HOI|Hao|Tuamotos|Hao Airport
"HOI"
字符串的行indexOf
和substring
。这里是适合您的代码段(文件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);
}
}
}
}
}
从假设您始终具有相同数量的字段开始,在情况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);
}
该代码将打印可以分配给您的不同变量的所有字段。