代码如下:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
public class App {
/**
* 保存 list 到指定文件
* @param list
* @param filePath
* @throws IOException
* @throws FileNotFoundException
*/
static void save(Listlist, String filePath) throws FileNotFoundException, IOException {
try ( FileOutputStream outputStream = new FileOutputStream(filePath);
OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream);
BufferedWriter writer = new BufferedWriter(streamWriter)
) {
for (String line : list) {
writer.write(line + System.lineSeparator());
}
}
}
public static void main(String[] args) throws IOException {
Listlist1 = new ArrayList<>();
Listlist2 = new ArrayList<>();
Listlist3 = new ArrayList<>();
File file = new File("d:/temp/0.txt");
try ( FileInputStream stream = new FileInputStream(file);
InputStreamReader streamReader = new InputStreamReader(stream);
BufferedReader reader = new BufferedReader(streamReader) ) {
String line = "";
while((line = reader.readLine()) != null) {
// 去除开始的数字
line = line.replaceFirst("\\d+", "");
if (line.contains("Organ")) {
// 包含 Organ 放入 list1
list1.add(line);
} else if (line.contains("Location")) {
// 包含 Location 放入 list2
list2.add(line);
} else if (line.contains("Person")) {
// 包含 Person 放入 list3
list3.add(line);
}
}
}
if (!list1.isEmpty()) {
save(list1, "d:/temp/1.txt");
}
if (!list2.isEmpty()) {
save(list2, "d:/temp/2.txt");
}
if (!list3.isEmpty()) {
save(list3, "d:/temp/3.txt");
}
}
}