0
    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) 行,即它读取并合并两个文件,但不对它们进行排序。有任何想法吗?

4

1 回答 1

1

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

于 2013-11-06T21:37:09.503 回答