您好,我的问题是如何按列过滤文本文件,我的意思是我想从行之间的范围中剪切文件。 我的文件包含此类数据:
284015160747447;8935901990807474474;
284015160747448;8935901990807474482;
284015160747449;8935901990807474490;
284015160747450;8935901990807474508;
284015160747451;8935901990807474516;
284015160747452;8935901990807474524;
284015160747453;8935901990807474532;
284015160747454;8935901990807474540;
284015160747455;8935901990807474557;
284015160747456;8935901990807474565;
284015160747457;8935901990807474573;
284015160747458;8935901990807474581;
284015160747459;8935901990807474599;
284015160747460;8935901990807474607;
284015160747461;8935901990807474615;
284015160747462;8935901990807474623;
284015160747463;8935901990807474631;
我希望用户能够过滤要从原始文件写入新创建的内容: 例如从 8935901990807474490 到 8935901990807474532,对于此数字,起始行和最后一行应在此范围内。
public class Test_read_file {
public static List<String> readFile() throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader("C:\\\\\\\\Users\\\\\\\\Admin\\\\\\\\Desktop\\\\\\\\Work Files\\\\\\\\314-WO0000001133814\\\\\\\\Cards\\\\\\\\MBD10760_182.out"))) {
List<String> listOfData = new ArrayList<>();
String d;
while ((d = br.readLine()) != null) {
listOfData.add(d);
}
return listOfData;
}
}
public static void writeFile(List<String> listOfData) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\\\\\\\Users\\\\\\\\Admin\\\\\\\\Desktop\\\\\\\\Work Files\\\\\\\\314-WO0000001133814\\\\\\\\Cards\\\\\\\\MBD10760_187.out"))) {
for (String str : listOfData) {
bw.write(str);
bw.newLine();
}
}
}
public static void main(String[] args) throws IOException {
List<String> data = readFile();
writeFile(data);
}
}
最佳答案
对您的代码进行以下更改:
使用扫描仪接受要过滤的值:
public static void main(String[] args) throws IOException { List<String> data = readFile(); Scanner sc = new Scanner(System.in); System.out.println("Enter range"); long num1 = sc.nextLong(); long num2 = sc.nextLong(); writeFile(data, num1, num2); sc.close(); }
因为您只想由第二列写入列,所以将其拆分 使用
;
然后仅将第一个索引添加到列表中。这可确保仅第二列的数字被添加到列表中。public static List<String> readFile() throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(PATH))) { List<String> listOfData = new ArrayList<>(); String d; while ((d = br.readLine()) != null) { String[] split = d.split(";"); // <-- change made here listOfData.add(split[1]); } return listOfData; } }
使用传入的范围,它只会写入属于该范围的数字 在此范围内。
public static void writeFile(List<String> listOfData, long num1, long num2) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter(OUT))) { for (String str : listOfData) { // change made here if (Long.valueOf(str) >= num1 && Long.valueOf(str) <= num2) { bw.write(str); bw.newLine(); } } } }
关于java - 如何通过java过滤文本文件并将结果保存到新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54387876/