我有一个文件,其中有数百万条记录。这里我想读取前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) {
}
}
}
最佳答案
您有多种选择:如果您想更新现有文件 - 同时读取和写入,您将需要 RandomAccessFile溪流。这样您就可以打开文件进行读取和写入。另一方面,更新同一文件而不保留原始文件可能存在风险,因为您的应用程序可能会在某个时候崩溃,并且您将留下损坏的文件。
另一种方法是获取一个新的临时文件并写入您想要保留在该文件中的部分,但如果您有数百万条记录,这可能效率不高。
关于java - 从文本文件中删除前 1000 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36199077/