此代码用于比较2个文本文件的内容, 但我需要首先验证,这两个文件的名称不相同。
你可以帮我解决这个问题吗? import java.io.*;
import java.util.*;
public class compare {
public static void main(String args[]) throws IOException {
try{
FileInputStream file1 = new FileInputStream(args[0]);
FileInputStream file2 = new FileInputStream(args[1]);
if(args.length != 2)
throw (new RuntimeException("Usage : java compare <filetoread> <filetoread>"));
if(args[0]==args[1]){
System.out.print("File name is identical");
}
else {
while (true) {
int a = file1.read();
int b = file2.read();
if (a!=b) {
System.out.print("File do not match");
break;
}
else{
System.out.print("Files match");
break;
}
}
}
}
catch(FileNotFoundException e){
System.out.print("File tidak ada");
}
catch(IOException e){
System.out.print("IO Error");
}
}
}
答案 0 :(得分:2)
解决方案是:
if (file1.getCanonicalPath().equals(file2.getCanonicalPath()) {
// the arguments refer to the same file.
}
请注意,与File.getAbsolutePath()
不同,File.getCanonicalPath()
方法会解析“。”和“..”路径名,解析Unix / Linux上的符号链接,并将Windows驱动器号转换为标准大小写。
答案 1 :(得分:1)
if(args[0].equals(args[1]))
将有助于比较字符串的内容而不是它们的地址。
实际上
if(file1.getCanonicalPath().equals(file2.getCanonicalPath())
更好(如果您可以获取File对象'new File(arg[0])
',然后可以将其用作FileInputStream
对象的参数):您将比较两个规范的规范化路径,而不是两个String例如,由具有潜在小写/大写差异的用户输入。见getCanonicalPath()
javadoc:
规范路径名既是绝对路径名也是唯一路径名。规范形式的精确定义取决于系统。如果需要,此方法首先将此路径名转换为绝对形式,就像调用
getAbsolutePath()
方法一样,然后以系统相关的方式将其映射到其唯一形式。这通常涉及从路径名中删除冗余名称,例如“.
”和“..
”,解析符号链接(在UNIX平台上),以及将驱动器号转换为标准情况(在Microsoft Windows平台上) 。
答案 2 :(得分:0)
尝试使用:
args[0].equals(args[1])