[英]comparing two files character by character
这是我的代码:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Type first file name to use: ");
String filename1 = console.nextLine();
System.out.print("Type second file name to use: ");
String filename2 = console.nextLine();
Scanner input1 = new Scanner(new File(filename1));
Scanner input2 = new Scanner(new File(filename2));
String s1 = input1.next();
String s2 = input2.next();
boolean similar=true;r
while(!input1.hasNext()&&!input2.hasNext()){
// this is where i am stuck. i need to compare the lines character by character, but i'm not sure how to do so. i can't use buffer method, or any really advanced methods since i am just a beginner, so sticking to the basic loops (while, iff, for.. ) is the only option i have
}
程序应提示用户输入两个文件名,并根据文件内容是否相同来打印true或false,并应逐字符检查文件,并忽略大小写(大写和小写)字母字符。 谢谢。
采用:
if (s1.equalsIgnoreCase(s2)) {
// All characters on the entire line are equal.
} else {
// There is a difference
}
它将一次一行地比较字符串。
您可以创建一个循环,但是这将需要更多代码,并且会导致性能降低。
一个又一个字符地字符,不允许当前的结构执行任何工作?
while(!input1.hasNext()&&!input2.hasNext())
{
char c1 = input1.next(".");
char c2 = input2.next(".");
if (c1!=c2)
{
//Files are not equal
}
}
如果愿意,可以使用Reader
实例逐个字符处理文件。 就像是 :
BufferedReader reader1 = new BufferedReader(new FileReader("fileName1"));
BufferedReader reader2 = new BufferedReader(new FileReader("fileName2"));
int char1; // from first file
int char2; // from second file
// loop until the end of either file is reached
while ((char1 = reader1.read()) != -1 && (char2 = reader2.read()) != -1) {
// convert current characters from both files to lowerCase
char lowerCase1 = Character.toLowerCase((char) char1);
char lowerCase2 = Character.toLowerCase((char) char2);
if (lowerCase1 != lowerCase2) {
System.out.println("your text files are different!");
return;
}
}
您应该这样做:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Type first file name to use: ");
String filename1 = console.nextLine();
System.out.print("Type second file name to use: ");
String filename2 = console.nextLine();
Scanner input1 = new Scanner(new File(filename1));
Scanner input2 = new Scanner(new File(filename2));
String s1 = input1.next();
String s2 = input2.next();
boolean similar=true;r
while(!input1.hasNext()&&!input2.hasNext()){
if (a.findInLine(".").compareToIgnoreCase(b.findInLine(".")) != 0) {
similar = false;
break;
}
}
if (similar && (a.hasNext() || b.hasNext())) // unequal sizes
similar = false;
System.out.println("Files are " + (similar ? "equal" : "unequal"));
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.