我正在尝试从File1(.txt)和File2(.txt)中获取输入,合并并排序两个文件中包含的整数,并创建第三个File3(.txt),其中包含文件1和2中的排序整数。
到目前为止,这是我的代码:
File input1 = new File("H:\\Desktop\\input1.txt");
Scanner scan = new Scanner(input1);
File input2 = new File("H:\\Desktop\\input2.txt");
int num;
while(scan.hasNextInt())
{
num = scan.nextInt();
final List<Integer> list = Arrays.asList(num);
Collections.sort(list);
System.out.println(list);
}
File1包含数字10、11、8、74、16。
我尝试的每个数组,我总是得到乱码的输出,所以我得到了这段代码。我得到输出,但未排序:
[10]
[11]
[8]
[74]
[16]
任何人都可以提供帮助或建议吗?
最佳答案
将列表移到循环外,这样就不会每次都初始化。还要删除final
关键字,因为它会改变大小。
要添加到List<Integer>
,请使用.add(element);
。这会将一个新元素添加到列表的末尾。
对第二个文件重复此逻辑。
填写完列表后,呼叫Collections.Sort(list);
。
创建新文件。遍历列表并将元素写入文件
关闭档案
在下面查看。 (我没有Java编译器atm,因此它可能无法正常工作)希望您能明白。
File input1 = new File("H:\\Desktop\\input1.txt");
Scanner scan = new Scanner(input1);
File input2 = new File("H:\\Desktop\\input2.txt");
int num;
List<Integer> list = new ArrayList<Integer>();
while(scan.hasNextInt())
{
num = scan.nextInt();
list.add(num);
}
scan = new Scanner(input2); // Point Scanner to new file
while(scan.hasNextInt()) // Loop through new file
{
num = scan.nextInt();
list.add(num);
}
Collections.sort(list); // sort list after populating it from both files
// Printing to file
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
for(int numberInList : list) { // Loop through sorted list and print out list to file
writer.println(numberInList);
}
writer.close(); // Close the file
关于java - 如何从文件排序整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46895324/