JAVA模糊搜索文件内容并将本行内容保存如一个txt中

294 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

JAVA模糊搜索文件内容并将本行内容保存如一个txt中

上代码

	//定义存入的位置
	public String path = "F:\\log\\1001.txt";
    public File f = new File(path);
    public File file = new File("F:\\log\\test.txt");
    public String keyword = "搜索条件"
    public void SearchKeyword(File file, String keyword) {
        //将文件的参数进行校验
        verifyParam(file, keyword);
        //按行读取
        LineNumberReader lineReader = null;
        try {
            lineReader = new LineNumberReader(new FileReader(file));
            String readLine = null;
            int lineNumber = 0;
            while ((readLine = lineReader.readLine()) != null) {
                int index = 0;
                int next = 0;
                int times = 0;
                while ((index = readLine.indexOf(keyword, next)) != -1) {
                    lineNumber += 1;
                    next = index + keyword.length();
                    times++;
                }
                if (times > 0) {
                	//截取此字段后面的内容(不需要正则进行转义)
                    readLine = readLine.substring(readLine.indexOf("截取此字段后面的内容"));
                    //截取此字段前面的内容
                    String readLine1 = readLine.substring(0, readLine.indexOf("截取此字段前面的内容"));
                    //将每一次读到的内容存入新的文件中
                    write2Txt(readLine1);
                }
            }
            System.out.println("一个" + lineNumber + "条");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            close(lineReader);
        }
    }

    /**
     * 对文件的内容以及搜索条件进行校验
     */
    private void verifyParam(File file, String keyword) {
        //对参数进行校验证
        if (file == null) {
            throw new NullPointerException("the file is null");
        }
        if (keyword == null || keyword.trim().equals("")) {
            throw new NullPointerException("the keyword is null or \"\" ");
        }

        if (!file.exists()) {
            throw new RuntimeException("the file is not exists");
        }
        if (file.isDirectory()) {
            throw new RuntimeException("the file is a directory,not a file");
        }
        if (!file.canRead()) {
            throw new RuntimeException("the file can't read");
        }
    }

    /**
     * 关闭流
     */
    private void close(Closeable able) {
        if (able != null) {
            try {
                able.close();
            } catch (IOException e) {
                e.printStackTrace();
                able = null;
            }
        }
    }

	/**
     * 将内容写入文件中
     */
    public void write2Txt(String str) throws IOException {
        FileWriter fw = null;
        fw = new FileWriter(f, true);
        BufferedWriter out = new BufferedWriter(fw);
        //转换为String类型
        out.write(str.toString());
        //每一行都写入
        out.newLine();
        out.close();
    }

创作不易请多多支持,更多详情请关注wx工作号:xvguo1127