首页 > 解决方案 > 如果满足条件则删除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);
    }

标签: javafile

解决方案


您可以在空间上拆分行,将第一个元素转换为 anint并与用户输入进行比较

while ((currentLine = reader.readLine()) != null) {
    String[] parts = line.split(" ");
    if (Integer.parseInt(parts[0]) == lineToRemove) {
        continue;
    }
    writer.write(currentLine + System.getProperty("line.separator"));
}

推荐阅读