java - 读取一个文件并检查其他文件中是否存在内容的最佳方法是什么
问题描述
我在不同的文件夹中有两个文件,例如 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();
}
}
解决方案
我建议你像这样使用 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
通常,您希望包含一些已经尝试过的代码,以便您也可以收到一些代码反馈。
推荐阅读
- jboss - jboss eap 7 - 使用资源适配器将消息发布到 IBM MQ
- java - 使用 ProcessBuilder 运行外部 Java 进程并给出堆大小
- python-3.x - 发送串行数据时程序卡住
- mysql - MySQL中模式的概念
- node.js - AWS DynamoDB 中的嵌套数组过滤器
- java - 使用输出目录 -o 选项时,TestRig / grun 会丢弃 java.lang.NoClassDefFoundError
- swiftui - 如何解决错误:xcode12 和 swiftui 中的“不能在不可变值上使用变异成员:'users' 是 get-only 属性”
- python - 计算字典的在线人数
- python - 使用 Keras/Tensorflow 数据加载器高效加载大型 .npy 文件 (>20GB)
- solr - SOLR 4.1.0 - 字段之间的日期查询