Java 读取和写入文本文件
package test_java; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.List; public class ReadWrite { public static void main(String [] args) { String filePath = "input.txt"; String destFilePath = "output.txt"; readWrite(filePath, destFilePath); } public static void readWrite(String filePath, String destFilePath) { List<String> report = Arrays.asList("Prevotella_intermedia", "Enterobius_vermicularis", "Parvimonas_micra", "Protopolystoma_xenopodis"); try { BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath)); // 读取文件 FileOutputStream fileOutputStream = new FileOutputStream(new File(destFilePath)); // 写入文件 String string; while((string = bufferedReader.readLine()) != null) { // 按行读取 if (string.split("\t")[0].trim().equals("species")) { fileOutputStream.write((string + "\n").getBytes()); // 将符合条件的行写入文件 } if (report.contains(string.split("\t")[0].trim())) { fileOutputStream.write((string + "\n").getBytes()); } } } catch (IOException e) { e.printStackTrace(); } } }