-1

Whenever I run my code, the inv.txt file changes from having 25 lines of the character 1 to nothing, could someone tell me what I'm doing wrong? PS the main class includes inventory.addItem();

 public class inventory {
File inventory = new File("Resources/inv.txt");
File db = new File("Resources/db.txt");
FileWriter write;
StringBuilder writethis;

public void addItem(int item, int slot){
    int i;
    Scanner scan = null;
    try {
        scan = new Scanner(inventory);
    } catch (FileNotFoundException e) {

        e.printStackTrace();
    }
    try {
        write = new FileWriter(inventory);
    } catch (IOException e) {

        e.printStackTrace();
    }
    for(i = 1; i < slot; i++)writethis.append(scan.nextLine());
    System.out.println(writethis.toString());
}
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
drdavehere
  • 21
  • 6

1 Answers1

2

Use write = new FileWriter(inventory, true);

It will append data to existing file. See the documentation on FileWriter Constructor for further details.

Sourabh Bhat
  • 1,793
  • 16
  • 21
  • Thats not it, seeing as I don't want it to append, and I also don't even try to write to the file in my code. – drdavehere Mar 16 '14 at 02:14
  • @drdavehere Yes, but as soon as it hits that line it will clear the file. Whether or not it writes to it. – imtheman Mar 16 '14 at 02:15
  • @imtheman Really? Thanks! I guess I'll just put that part of the code after I've read the file, etc. – drdavehere Mar 16 '14 at 02:17
  • Actually when you call `new FileWriter(inventory);` a new empty file is created. `new FileWriter(inventory, true);` will prevent your program from creating a new file. – Sourabh Bhat Mar 16 '14 at 02:18
  • @drdavehere That is a good idea. Also, make sure you close the Scanner before you start writing. – imtheman Mar 16 '14 at 02:18
  • Ok, but then, won't it just append to the file? I want it to replace the file with writethis.toString(); (Not something I've written in the code) – drdavehere Mar 16 '14 at 02:19
  • @drdavehere Yes, it will append. I recommend you just create the `FileWriter` after you get all of the data. – imtheman Mar 16 '14 at 02:23
  • 1
    You should really consider using the new API; for instance, `Files.newBufferedWriter()`. With the correct options, you will select to append to the file, create it if it doesn't exist, etc. Ditch the old file API. – fge Mar 16 '14 at 02:24