JAVA deletes the specified line in the txt file according to the line number or line content

I have nothing to do. I saw a small partner in the java group asking about deleting lines. I learned about this knowledge and wrote an example as a souvenir.


import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class Test {
    
    


    /**
     * 根据行数删除某一指定行
     *
     * @param file             txt文件路径
     * @param lineNumber       要删除的行
     * @param retainRemoveLine 是否保留删除的行(保留:留下一个空白行,不保留:下面的行自动上移)
     */
    public static Map<String, Object> removeLineForLineNumber(String file, int lineNumber, boolean retainRemoveLine) {
    
    

        Map<String, Object> map = new HashMap<>(8);
        map.put("success", false);
        map.put("error", "");

        try {
    
    
            //获取原文件
            File oldFile = new File(file);
            if (!oldFile.isFile()) {
    
    
                map.put("error", "该文件未找到:" + file);
                return map;
            }
            
			// 判断一下文件的总行数,比较lineNumber是否合理
            if(lineNumber>Files.lines(Paths.get(file)).count()){
    
    
                map.put("error", "要删除的行超过文件总行数");
                return map;
            }

            //构造临时文件
            File newFile = new File(oldFile.getAbsolutePath() + ".tmp");
            BufferedReader br = new BufferedReader(new FileReader(file));
            PrintWriter pw = new PrintWriter(new FileWriter(newFile));
			
            String lineStr = null;//某一行的值
            int lineCount = 0;//行数
            while ((lineStr = br.readLine()) != null) {
    
    
                lineCount++;
                if (lineCount != lineNumber) {
    
    
                    pw.println(lineStr);
                    pw.flush();
                } else {
    
    
                    //保留删除行
                    if (retainRemoveLine) {
    
    
                        pw.println("");
                    }
                    pw.flush();
                }
            }

            pw.close();
            br.close();

            //删除原文件
            if (!oldFile.delete()) {
    
    
                map.put("error", "该文件删除失败:" + file);
                return map;
            }

            //重命名
            if (!newFile.renameTo(oldFile)) {
    
    
                map.put("error", "该文件重命名失败:" + file);
                return map;
            }

            map.put("success", true);
        } catch (FileNotFoundException ex) {
    
    
            ex.printStackTrace();
            map.put("error", ex.getMessage());
        } catch (IOException ex) {
    
    
            ex.printStackTrace();
            map.put("error", ex.getMessage());
        }
        return map;
    }


    /**
     * 根据行内容删除某一指定行
     *
     * @param file             txt文件路径
     * @param lineContent      要删除的行内容
     * @param retainRemoveLine 是否保留删除的行(保留:留下一个空白行,不保留:下面的行自动上移)
     */
    public static Map<String, Object> removeLineForLineContent(String file, String lineContent, boolean retainRemoveLine) {
    
    

        Map<String, Object> map = new HashMap<>(8);
        map.put("success", false);
        map.put("error", "");

        try {
    
    
            //获取原文件
            File oldFile = new File(file);
            if (!oldFile.isFile()) {
    
    
                map.put("error", "该文件未找到:" + file);
                return map;
            }

            //构造临时文件
            File newFile = new File(oldFile.getAbsolutePath() + ".tmp");
            BufferedReader br = new BufferedReader(new FileReader(file));
            PrintWriter pw = new PrintWriter(new FileWriter(newFile));

            String line = null;//某一行的值
            while ((line = br.readLine()) != null) {
    
    
                //这里我用了equals,可以根据自己的需要改成index或者其他的
                if (!line.trim().equals(lineContent)) {
    
    
                    pw.println(line);
                    pw.flush();
                } else {
    
    
                    //保留删除行
                    if (retainRemoveLine) {
    
    
                        pw.println("");
                    }
                    pw.flush();
                }
            }

            pw.close();
            br.close();

            //删除原文件
            if (!oldFile.delete()) {
    
    
                map.put("error", "该文件删除失败:" + file);
                return map;
            }

            //重命名
            if (!newFile.renameTo(oldFile)) {
    
    
                map.put("error", "该文件重命名失败:" + file);
                return map;
            }

            map.put("success", true);
        } catch (FileNotFoundException ex) {
    
    
            ex.printStackTrace();
            map.put("error", ex.getMessage());
        } catch (IOException ex) {
    
    
            ex.printStackTrace();
            map.put("error", ex.getMessage());
        }
        return map;
    }


    public static void main(String[] args) {
    
    
        System.out.println(Test.removeLineForLineNumber("d:/test.txt",3,false));
        System.out.println(Test.removeLineForLineContent("d:/test.txt", "a", true));
    }
}

Guess you like

Origin blog.csdn.net/iloki/article/details/114088786