java将两个带整数的文本文件合并为一个文本文件
我需要将两个文本文件合并成一个合并文本文件。文件仅由数字组成,然后必须按升序列出数字。我已经把它编码成这样,但是,我不能让它加上最后一个数字,它给了我一个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
# 1 楼答案
您尝试使用
trim()
Integer.parseInt(blabla.trim());
,因为您的数字有一个或多个空格字符,所以解析失败示例代码:
public static void main(String[]args)抛出了畸形的DurLexception,IOException{
}
# 2 楼答案
你需要考虑当一个文件或另一个文件用完时该怎么做。
BufferedReader。readLine()在EOF上返回一个null,因此您将查找null
逻辑是这样的
# 3 楼答案
假设有两个列表包含第一个和第二个文件的整数值, 如果将这两个文件都读入列表,比如lst1和lst2,那么合并到lst3应该很容易:
然后可以将
lst3
的内容写入输出文件免责声明:我使用记事本编写了代码——你可能需要“修补”一下它;)