java - 如果满足条件则删除java文件中的一行
问题描述
我正在做一个练习,我必须向用户询问部门编号,然后删除包含部门 ID 的行。到目前为止,我只设法删除了整条线,但如果不是按行号,也不是按部门号。该文件包含以下信息:
1 | bird | Barcelona
2 | rabbit | Dublin
3 | turtle | Malaga
4 | bird | Madrid
7 | turtle | Dublin
我的代码如下:
public static void borrarLinea() throws IOException {
File inputFile = new File("Departamentos.dat");
File tempFile = new File("DepartamentosTemp.dat");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
Scanner entrada = new Scanner(System.in);
int lineToRemove;
System.out.println("¿Que número de departamento deseas borrar?");
lineToRemove = entrada.nextInt();
entrada.nextLine();
String currentLine;
int count = 0;
while ((currentLine = reader.readLine()) != null) {
count++;
if (count == lineToRemove) {
continue;
}
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete();
tempFile.renameTo(inputFile);
}
解决方案
您可以在空间上拆分行,将第一个元素转换为 anint
并与用户输入进行比较
while ((currentLine = reader.readLine()) != null) {
String[] parts = line.split(" ");
if (Integer.parseInt(parts[0]) == lineToRemove) {
continue;
}
writer.write(currentLine + System.getProperty("line.separator"));
}
推荐阅读
- tensorflow - Keras 置换层与重塑层
- python - Python 随机选择在每个循环迭代中返回相同的结果
- docker - docker 容器上的环境变量不会被覆盖
- python - mognoengine 和 bson 包不能一起工作
- sas - 使用 PROC SQL (Teradata) 获取过去 1 小时内的记录
- javascript - 自动计算器
- linux - 打开 AppImage 什么都不做。我能做些什么?
- python - 将 list[0], list[1], list[2],... 压缩成一个简单的语句
- java - 如何解决“无法应用适配器”错误?
- spring-cloud-stream - 了解 Spring Cloud Stream Kafka 和 Spring Retry