您没有回答@Steve 关于不同长度数字的情况,我假设您想根据字符顺序比较数字。另外,我假设文件总是在一行中包含三个字符串,由一个空格分隔。
鉴于此,我希望这会有所帮助:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class FindDifference {
static File f = null;
ArrayList<String> inputs = new ArrayList<String>();
static String x1 = null;
static String x2 = null;
static String x3 = null;
private static ArrayList<String> getDifferenceList() {
ArrayList<String> ret = new ArrayList<String>();
if (x1 == null || x1.isEmpty()
|| x2 == null || x2.isEmpty()
|| x3 == null || x3.isEmpty()) {
ret.add(x1);
ret.add(x2);
ret.add(x3);
return ret;
}
int index = 0;
while (index < x1.length()
&& index < x2.length()
&& index < x3.length()) {
if (x1.charAt(index) != x2.charAt(index)
|| x1.charAt(index) != x3.charAt(index)) {
break;
}
index++;
}
ret.add(x1.substring(index, x1.length()));
ret.add(x2.substring(index, x2.length()));
ret.add(x3.substring(index, x3.length()));
return ret;
}
public static void main(String[] args) {
if (args.length > 0) {
f = new File(args[0]);
} else {
System.out.println("Please supply file path.");
return;
}
String line;
BufferedReader buffreader = null;
try {
buffreader = new BufferedReader(new FileReader(f));
while (( line = buffreader.readLine()) != null) {
String[] parts = line.split(" ");
x1 = (parts[0]);
x2 = (parts[1]);
x3 = (parts[2]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<String> output = getDifferenceList();
try {
System.out.println(output.get(0));
System.out.println(output.get(1));
System.out.println(output.get(2));
} catch (Exception e) {
e.printStackTrace();
}
}
}
我做了SSCCE。您只能在代码中使用 getDifferenceList(提供 x1、x2、x3 作为字段)(在需要的地方删除“静态”)。
编辑
正如我所说,您可以在任何范围(包括 Android 应用程序)中使用 getDifferenceList。我单独复制此方法,只需将其复制粘贴到您想要的任何类中,然后通过文件路径调用它:
ArrayList<String> getDifferenceList(String filePath) {
File f = new File(filePath);
String line, x1 = null, x2= null, x3 = null;
BufferedReader buffreader = null;
try {
buffreader = new BufferedReader(new FileReader(f));
while (( line = buffreader.readLine()) != null) {
String[] parts = line.split(" ");
x1 = (parts[0]);
x2 = (parts[1]);
x3 = (parts[2]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<String> ret = new ArrayList<String>();
if (x1 == null || x1.isEmpty()
|| x2 == null || x2.isEmpty()
|| x3 == null || x3.isEmpty()) {
ret.add(x1);
ret.add(x2);
ret.add(x3);
return ret;
}
int index = 0;
while (index < x1.length()
&& index < x2.length()
&& index < x3.length()) {
if (x1.charAt(index) != x2.charAt(index)
|| x1.charAt(index) != x3.charAt(index)) {
break;
}
index++;
}
ret.add(x1.substring(index, x1.length()));
ret.add(x2.substring(index, x2.length()));
ret.add(x3.substring(index, x3.length()));
return ret;
}