从文本文件

时间:2016-03-24 11:28:10

标签: java java-io

我有一个文件有数百万的记录。在这里,我想先阅读2000条记录并在阅读后删除它们。 我能够阅读记录,但请告诉我如何删除。

public class Files {


    public static void files(int index) throws IOException {
        try {

            //numbers num = new numbers();
            BufferedReader br = null;
            BufferedWriter bw = null;
            try {

                String sCurrentLine = "";
                br = new BufferedReader(new FileReader("data.txt"));
                bw = new BufferedWriter(new FileWriter("File_2.txt"));

                int i = 0;
                while ((sCurrentLine = br.readLine()) != null && i < index) {
                    System.out.println(++i + " " + sCurrentLine);
                    bw.write(sCurrentLine);
                    bw.write(System.getProperty("line.separator"));
                    //sCurrentLine = br.readLine();
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    br.close();
                    bw.close();
                    if (br != null) {
                        br.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

        } catch (Exception e) {

        }
    }

}

1 个答案:

答案 0 :(得分:0)

您有以下几种选择:如果您想要更新现有文件 - 同时读取和写入,则需要RandomAccessFile流。有了它,你可以打开文件 - 阅读和写作。另一方面,在不保留原始文件的情况下更新同一文件可能会有风险,因为您的应用程序可能会在某些时候崩溃并且您将留下损坏的文件。

另一种方法是获取一个新的临时文件并编写你想要保存在该文件中的部分,但是如果你有数百万条记录,这可能效率不高。

相关问题