首页 > 解决方案 > 读取一个文件并检查其他文件中是否存在内容的最佳方法是什么

问题描述

我在不同的文件夹中有两个文件,例如 inputfolder1 和 inputfolder2 ,现在我需要检查 inputfolder1 文件内容是否存在于 inputfolder2 文件中,如果没有则创建新的输出文件。

public class CompareContent {


public static void main(String[] args) {

    String path="";
    Path filePath = Paths.get(path+"inputfolder1", "data.txt");

    try (Stream<String> lines = Files.lines( filePath )) 
    {

        lines.forEach(p->{

            System.out.println(p);
            try {
                boolean flag=FileUtils.readFileToString(new File(path+"inputfolder2\\data2.txt")).contains(p);
              System.out.println(flag);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        });


    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }
}

标签: java

解决方案


我建议你像这样使用 File I/O 包:

验证文件是否存在:

boolean fileExists = java.nio.file.File.exists( Paths.get( "inputfolder1/"+ fileName ));

要验证是否有内容,可以使用 Path.size(),它将返回文件的大小:

int fileSize = Path.size( Paths.get( "inputfolder1/" + fileName ));

您可能会发现阅读以下内容很有用:

https://docs.oracle.com/javase/tutorial/essential/io/check.html

https://docs.oracle.com/javase/tutorial/essential/io/file.html

一般来说,请查看完整的文件 I/O 教程:

https://docs.oracle.com/javase/tutorial/essential/io/fileio.html

通常,您希望包含一些已经尝试过的代码,以便您也可以收到一些代码反馈。


推荐阅读