// Create file
FileWriter fstream = new FileWriter(fileName, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(c.toString());
//Close the output stream
out.close();
// Code I used to read record I am using | as a seperator name and id
String fileName = folderPath + "listCatalogue.txt";
String line = "";
Scanner scanner;
String name, id;
scanner = new Scanner(fileName);
System.out.println(scanner.hasNextLine());
while (scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
StringTokenizer st = new StringTokenizer(line, "|");
name = st.nextToken();
id = st.nextToken();
catalogues.add(new Catalogue(name, id));
}
上面是创建文件和读取文件的代码,如何删除某些记录,在File中,我从谷歌找到的是删除文件但不删除某些记录示例我提供的名称,如果匹配删除此记录。以及修改那条记录?是否可以使用File?
进行修改记录答案 0 :(得分:0)
由于多种原因,删除文件中的某些记录是不可能的。
首先,记录是您的应用程序级别术语。文件系统只知道字节序列。您用于访问文件的第二个流也是不支持删除的抽象。
那么,解决方案是什么。
mark()
和skip()
方法。如果数据结构允许检索要删除的记录的位置,则可以通过调用skip()
立即到达此位置。问题是要删除。要解决它,您应该创建允许将记录标记为已删除的数据结构。在这种情况下,您不会真正删除记录,只需将其标记为已删除。其他解决方案是在记录上写入特殊(例如null)值,但您的读者必须能够跳过此类空值。
此解决方案有一个缺点:如果删除许多记录,文件将不会更小。Variant:您可以使用RandomAccessFile API。您也可以使用FileChannel。