java读取txt文件遇到空格对内容定列,将第二列以abc开头的行内容另存一文件中
发布网友
发布时间:2022-05-22 10:19
我来回答
共1个回答
热心网友
时间:2024-03-08 01:23
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class $ {
public static void main(String[] args) {
File file = new File("D://test.txt");
BufferedReader in = null;
PrintWriter out = null;
try {
in = new BufferedReader(new FileReader(file));
String str = "";
String result = "";
while ((str = in.readLine()) != null && str.length() > 0) {
//多个连续空格替换成一个空格然后通过空格分割成数组
String[] arr = str.replaceAll(" +", " ").split(" ");
//数组第二个
if (arr.length > 1 && arr[1].startsWith("abc")) {
result += str + "\r\n";
}
}
out = new PrintWriter("D://test1.txt");
out.write(result);
System.out.println(result);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
out.flush();
out.close();
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}