0

I have this file

1007    book1           5      3
1004    book2           4      1
1003    book3           3      0
1002    book4           2      1

and I am trying to delete the book number 1004 from the file, but before that I let the user enter the number of the book that he wants to delete. First check if the book exists in the file or not, if the book is exists I delete it if not show "the book does not exists".

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("%8d\t%-30s\t%8d\t%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();

I am trying to print all the file with out the book I have deleted.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3435095
  • 45
  • 2
  • 9

3 Answers3

0

You will need a book class, like this:

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.)
}

When you use scanner to read the file, read them into an arraylist of type Book. When user enter a number, use a for loop to find the Book that matches that number, and remove that book object from your arraylist.

Also, try to keep data in memory and not write files too often. Writing files to disks is very inefficient comparing with changing data in memory. Once user is done with all his/her operations, you can use a printwriter to write the data to your file.

To read your file into this array of objects, you can do this:

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;
}

Remember to import proper dependency at the beginning of your class. Wish it helps!

  • How can I read the file into array of objects ?? – user3435095 May 04 '14 at 23:25
  • I edited my responses. See above. I would suggest not reading them into array, unless you know how many Book objects to expect. ArrayList is a better approach when you have no clue about how many Book-s to deal with –  May 05 '14 at 00:34
0

I'd recommend to use a Map to store each line as value and the Id as the key only once. That way you don't have to reopen the file and read it each time you want to remove or add an entry, all you have to do is remove it and add it to the map. Once you are done, you can overwrite the old file you have by the values stored in the map or just create a new temp file to hold the data, delete the old file and then rename the temp file with old file's name

Amson
  • 74
  • 8
0

Store all the lines you would like to save in a String and close the scanner. Create a printwriter, print the string to the file and close it.

Example code:

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();
PalSivertsen
  • 384
  • 2
  • 11