java 根据条件读取整行 并保存到新的文件
public class IoTest {
public static void main(String[] args) {
File file1 = new File("D:\\spring.log");
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
try {
fis = new FileInputStream(file1);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
String lineTxt = null;
List<String> list = new ArrayList<>();
while ((lineTxt = br.readLine()) != null) {
if (lineTxt.contains("/20002104/2/12")) {
list.add(lineTxt);
}
}
writeListToFile(list,"20002104-2-12");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (isr != null) {
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void writeListToFile(List<String> listStr,String fileName) {
File file = new File("D:"+fileName+".log");
if (!file.exists()) {
try {
file.createNewFile();
System.out.println("文件"+file.getName()+"不存在已为您创建!");
} catch (IOException e) {
System.out.println("创建文件异常!");
e.printStackTrace();
}
} else {
System.out.println("文件"+file.getName()+"已存在!");
}
for (String str : listStr) {
FileOutputStream fos = null;
PrintStream ps = null;
try {
fos = new FileOutputStream(file,true);
ps = new PrintStream(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String string = str +在这里插入代码片 "\r\n";
ps.print(string);
ps.close();
}
System.out.println("文件写入完毕!");
}