我需要将两个文本文件合并为一个合并文本文件。文件仅由数字组成,并且数字必须按升序列出。我已经对其进行了编码来执行此操作,但是,我无法让它添加最后一个数字,并且它给了我一个 numberformatexception 错误。我相信这是因为我的最后一个数字没有任何可比较的内容,所以我无法将其添加到列表中。我不确定如何添加最后一个数字,当它也没有什么可以比较时(我很确定我需要另一个 if 语句,我只是不知道该怎么做)并且我不知道正确的 while 语句是什么是的,但是程序使用我使用的 while 语句正确运行,没有最后一个数字。
public static void main(String[] args)
{
FileReader file1 = null;
FileReader file2 = null;
BufferedReader readfile1 = null;
BufferedReader readfile2 = null;
FileWriter fileout = null;
PrintWriter dataout;
String fname1 = "list1.txt";
String fname2 = "list2.txt";
int md = 0;
int file1num = 0;
int file2num = 0;
String file1str;
String file2str;
try
{
file1 = new FileReader(fname1);
}
catch
(FileNotFoundException xyz)
{
System.out.println("File not found: " + fname1);
System.exit(-1);
}
catch
(IOException abc)
{
System.out.println("IOException: caught");
System.exit(-1);
}
readfile1 = new BufferedReader(file1);
try
{
readfile2 = new FileReader(fname2);
}
catch
(FileNotFoundException xyz)
{
System.out.println("File not found: " + fname2);
System.exit(-1);
}
catch
(IOException abc)
{
System.out.println("IOException: caught");
System.exit(-1);
}
readfile2 = new BufferedReader(file2);
try
{
fileout = new FileWriter("merged.txt");
}
catch(IOException adc)
{
System.out.println("file error");
System.exit(-1);
}
dataout = new PrintWriter(fileout);
file1str = file1.readLine();
file1num = Integer.parseInt(file1str);
file2str = file2.readLine();
file2num = Integer.parseInt(file2str);
while(md !=-1)
{
if(file1num<file2num)
{
md=file1num;
file1str = file1.readLine();
file1num = Integer.parseInt(file1str);
}
if(file2num<file1num)
{
md=file2num;
file2str = file2.readLine();
file2num = Integer.parseInt(file2str);
}
if(file1num==file2num)
{
md=file1num;
file1str = file1.readLine();
file1num = Integer.parseInt(file1str);
}
}
所以我知道,在读取文件 1 中的最后一个 int 后,它将返回 null,这意味着文件 2 无法将其自身与其他任何内容进行比较,我相信这就是我的问题所在。问题在于 while 语句及其中包含的内容。另外,我不能使用任何数组或类似的东西,它必须是简单的读取两个文件,比较,将最小的数字添加到合并文件中。
输入示例:
文件1:
1
2
3
4
6
8
文件2:
3
5
6
8
9
预期输出:
1
2
3
3
4
5
6
6
8
8
9
最佳答案
您需要考虑当一个文件或另一个文件用完时该怎么办。
BufferedReader.readLine() 在 EOF 上返回 null,因此您将寻找 null。
逻辑看起来像这样
str1 = read file1
num1 = parse( str1 ) //parse() should be a method that can properly handle a null
str2 = read file2 //and return something appropriate, like -1, when null
num2 = parse( str2 ) //is encountered
while str1 != null || str2 != null
if str2 == null || num1 < num2
write num1
str1 = read file1
num1 = parse( str1 )
else if str1 == null || num1 > num2
write num2
str2 = read file2
num2 = parse( str2 )
else if num1 == num2
write num1
write num2
str1 = read file1
num1 = parse( str1 )
str2 = read file2
num2 = parse( str2 )
关于java - 将两个带有整数的文本文件合并为一个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18925988/