我有这个文件
1007 book1 5 3
1004 book2 4 1
1003 book3 3 0
1002 book4 2 1
,我试图从文件中删除书号1004,但在此之前,我让用户输入他想要删除的书号。首先检查书在文件中是否存在,如果书存在,则删除它,否则显示"书不存在"。
Scanner kb = new Scanner(System.in);
FileInputStream book = new FileInputStream("input.txt");
Scanner infile = new Scanner(book);
FileOutputStream out = new FileOutputStream("output.txt");
PrintWriter pw = new PrintWriter(out);
boolean found = false;
System.out.print("Enter the bookID : ");
int bID = kb.nextInt();
while(infile.hasNext()){
int id = infile.nextInt();
String title = infile.next();
int quantity = infile.nextInt();
int bQuantity = infile.nextInt();
if(bID == id){
found = true;
}
if(found == true){
pw.printf("%8dt%-30st%8dt%8d", infile.nextInt(), infile.next(), infile.nextInt(), infile.nextInt());
infile.nextLine();
System.out.println("The book has been deleted");
break;
}
}
if(found == false)
System.out.print("Not found");
pw.close();
infile.close();
我正在试着打印所有文件,不包括我删除的那本书。
您需要一个book类,如下所示:
public class Book {
private int series;
private String name;
private int intA;
private int intB;
public Book(int series,String name, int intA, int intB) {
this.series = series;
this.name = name;
this.intA = intA;
this.intB = intB;
}
....
.... (add other methods as needed, you will definitely need a
toString() method, and getIntA(), getIntB(), getSeriesNum(),
getName() etc.)
}
当使用scanner读取文件时,将它们读入Book类型的数组列表中。当用户输入数字时,使用for循环查找与该数字匹配的Book,并从数组列表中删除该Book对象。
另外,尽量将数据保存在内存中,不要太频繁地写文件。与更改内存中的数据相比,将文件写入磁盘的效率非常低。一旦用户完成了他/她的所有操作,你就可以使用打印机将数据写入你的文件。
要将文件读入对象数组,可以这样做:public static ArrayList<Book> readbooklist() {
ArrayList<Book> booklist = new ArrayList<Book>();
File file = new File("path/filename.fileextension");
try {
Scanner scnr = new Scanner(file);
while (scnr.hasNextLine()) {
String entry = scnr.nextLine();
String [] parts = entry.split("t"); // Depends on how data was delimited
int series = Integer.parseInt(parts[0]);
int intA = Integer.parseInt(parts[2]);
int intB = Integer.parseInt(parts[3]);
Book single = new Book(series, parts[1], intA, intB);
booklist.add(single);
}
scnr.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found!");
}
return booklist;
}
记得在你的类开始时导入适当的依赖。希望能有所帮助!
我建议使用Map将每行存储为值,将Id存储为键,仅存储一次。这样,您就不必在每次想要删除或添加条目时重新打开文件并读取它,您所要做的就是删除它并将其添加到映射中。完成后,可以用存储在映射中的值覆盖旧文件,或者创建一个新的临时文件来保存数据,删除旧文件,然后用旧文件名
将想要保存的所有行存储在String中并关闭扫描器。创建一个打印机,将字符串打印到文件中并关闭它。
示例代码:
File file = new File("yourTextFile.txt");
Scanner in = new Scanner(file);
String saveThisToFile = "";
while (in.hasNext()) {
String temp = in.nextLine();
if (condition to be true if you whant to keep this line) {
saveThisToFile += temp + "n";
}
}
in.close();
PrintWriter printWriter = new PrintWriter(file);
printWriter.print(saveThisToFile);
printWriter.close();