gpt4 book ai didi

java - 使用 arrayList 对行进行排序

转载 作者:行者123 更新时间:2023-12-01 13:52:57 25 4
gpt4 key购买 nike

    import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class part2
{

@SuppressWarnings("resource")
public static void main(String[] args) throws IOException
{
File f1 = new File("one.txt");
File f2 = new File("two.txt");

BufferedReader fr1 = null;
BufferedReader fr2 = null;
//BufferedReader fr3 = null;
BufferedWriter fw = null;

fr1 = new BufferedReader(new FileReader("one.txt"));
fr2 = new BufferedReader(new FileReader("two.txt"));
fw = new BufferedWriter(new FileWriter("res.txt"));


String line1 = fr1.readLine();
String line2 = fr2.readLine();


// merging two files into one
while (line1 != null)
{
fw.write(line1);
fw.newLine();

line1 = fr1.readLine();

}

while (line2 != null)
{
fw.write(line2);
fw.newLine();

line2= fr2.readLine();

}
fw.close();

// sorting a new file

BufferedReader fr3 = null;
BufferedWriter fw1 = null;

fw1 = new BufferedWriter(new FileWriter("res1.txt"));
fr3 = new BufferedReader(new FileReader("res.txt"));

String line3 = fr3.readLine();

ArrayList<String> lineList = new ArrayList<String>();
while (line3 != null)
{
lineList.add(line3);
line3 = fr3.readLine();
}


Collections.sort(lineList);

for(int i=0; i<lineList.size(); i++)
{
fw1.write(lineList.get(i) + "\n");
//line3 = fr3.readLine();

}



}
}

我试图将两个文件合并到“res.txt”中,然后按字母顺序对合并的文件进行排序(并将排序后的行放入“res1.txt”中)。一切正常,直到排序,确切地说是 while (line3 != null) 行,即它读取并合并两个文件,但不对它们进行排序。有什么想法吗?

最佳答案

在退出程序之前关闭 fw1,或者在刷新缓冲区内容之前将其从内存中删除。

关于java - 使用 arrayList 对行进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19822931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com