Find a line in a file and remove it

后端 未结 16 1684
谎友^
谎友^ 2020-11-22 13:06

I\'m looking for a small code snippet that will find a line in file and remove that line (not content but line) but could not find. So for example I have in a file following

16条回答
  •  渐次进展
    2020-11-22 13:49

    public static void deleteLine(String line, String filePath) {
    
        File file = new File(filePath);
    
        File file2 = new File(file.getParent() + "\\temp" + file.getName());
        PrintWriter pw = null;
        Scanner read = null;
    
        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel src = null;
        FileChannel dest = null;
    
        try {
    
    
            pw = new PrintWriter(file2);
            read = new Scanner(file);
    
            while (read.hasNextLine()) {
    
                String currline = read.nextLine();
    
                if (line.equalsIgnoreCase(currline)) {
                    continue;
                } else {
                    pw.println(currline);
                }
            }
    
            pw.flush();
    
            fis = new FileInputStream(file2);
            src = fis.getChannel();
            fos = new FileOutputStream(file);
            dest = fos.getChannel();
    
            dest.transferFrom(src, 0, src.size());
    
    
        } catch (IOException e) {
            e.printStackTrace();
        } finally {     
            pw.close();
            read.close();
    
            try {
                fis.close();
                fos.close();
                src.close();
                dest.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            if (file2.delete()) {
                System.out.println("File is deleted");
            } else {
                System.out.println("Error occured! File: " + file2.getName() + " is not deleted!");
            }
        }
    
    }
    

提交回复
热议问题