5

The actual problem will be addressed a bit further down :), thanks.

I'm fairly new to Java (nearly through a 400 page book).

I'm not really that familiar with the API yet.

This is my best shot at reading a .txt file and checking if there are any of the collected data that already is stored in the .txt file. If that is the case, the data will be removed from the data collection, and the data that isn't already found in the .txt will be added.

Some variables:

public String[] names;
public int[] levels;
public int[] IDs;

public ArrayList<String> line = new ArrayList<String>();
public ArrayList<RSNPC> monsterList = new ArrayList<RSNPC>();
public ArrayList<String> monstersToAdd = new ArrayList<String>();

The method that checks the existing .txt file:

    private void checkForLine() {
     try{
         // Create file 
        File file = new File(getCacheDirectory() + "output.txt");
        RandomAccessFile out = new RandomAccessFile(file, "rw");
        for(int i = 0; i < file.length(); i++){
            line.add(out.readLine());
        }
        for(String monster : monstersToAdd){    
            if(line.contains(monster)){
                monstersToAdd.remove(monster);
            }
        }
        //Close the output stream
        out.close();
     }catch (Exception e){//Catch exception if any
         System.err.println("Error: " + e.getMessage());
         }
     }

The method that then finally saves the information that the checkForLine() defined (the one already not in the file):

private void saveToFile() {
     try{
         // Create file 
        BufferedWriter out = new BufferedWriter(new FileWriter(getCacheDirectory() + "output.txt"));
        for(String a : monstersToAdd){
            out.write(a);
            out.newLine();
            log("Wrote " + a + "to file");
        }
         //Close the output stream
         out.close();
         }catch (Exception e){//Catch exception if any
         System.err.println("Error: " + e.getMessage());
         }
     }

The order of execution:

        getNPCS();
    getNames(monsterList);
    getLevels(monsterList);
    getIDs(monsterList);
    combineInfo();
    checkForLine();
    saveToFile();

The problem however, is that it doesn't correctly check for the .txt file for information. I can see that because it just saves whatever it observes over and over again, not sorting anything away. This was the only way I could think of with my limited knowledge, and it didn't work.

For those wondering: This is a script for a bot called RSbot that plays the game called RuneScape. I don't actually use the bot, but I wanted to do this for the exercise.

I can paste the entire script if that would clear up things further.

I really appreciate any help, and will of course remember to select the answer that I used (if anyone bothers helping out ;) ).

Thanks.

Mike Haye
  • 793
  • 3
  • 12
  • 22
  • _"not sorting anything away"_ - I don't see any actual code in here that performs a sort. – Matt Ball Jun 15 '11 at 19:33
  • @Matt Ball "filtering" -- That's why there is no CME ;) –  Jun 15 '11 at 19:34
  • 2
    It is recommended to write `List x = new ArrayList()` instead of `ArrayList y = new ArrayList()` code to the iterface, not the implementation. :) – OscarRyz Jun 15 '11 at 19:34
  • @pst: I was hoping that readLine() would actually just return the line it read as a string, which would match the monster, but I can hear from you that it doesn't :/.. can't really seem to find any other useful methods atm. – Mike Haye Jun 15 '11 at 19:39
  • @Mike: It would. pst is worried about the end-of-line character, but the [API](http://download.oracle.com/javase/1.4.2/docs/api/java/io/RandomAccessFile.html#readLine()) is pretty clear about discarding them. You can always call [trim](http://download.oracle.com/javase/6/docs/api/java/lang/String.html#trim()) to really make sure there's no extra whitespace. – trutheality Jun 15 '11 at 19:54
  • BTW I do not understand why you are using `RandomAccessFile` (in read-write mode!) to just read a file, line-by-line. `BufferedReader out = new BufferedReader(new FileReader(getCacheDirectory() + "output.txt"));` is perfectly sufficient. (You probably want to change its name to `in`, though ;-) – Matt Ball Jun 15 '11 at 20:53

2 Answers2

6
for(String monster : monstersToAdd){    
    if(line.contains(monster)){
        monstersToAdd.remove(monster);
    }
}

will throw a ConcurrentModificationException if line.contains(monster) is true, and monstersToAdd contains monster. The only safe way to remove an element from a collection while iterating is to use Iterator:

for(Iterator<String> iter = monstersToAdd.iterator(); iter.hasNext();){
    String monster = iter.next();
    if (line.contains(monster)) iter.remove();
}

Edit

@trutheality points out

Actually, a much simpler way to accomplish the same thing is monstersToAdd.removeAll(line);

So you can replace the for loop with one line of code.

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 1
    @trutheality Note that `monstersToAdd` is being *iterated* in the loop it is (potentially) modified inside. The `contains` (or `line`) is not relevant. –  Jun 15 '11 at 19:35
  • @truth: look at the code again. `monster` is removed from the collection that is being iterated. – Matt Ball Jun 15 '11 at 19:36
  • @pst oh, for some reason I thought it was iterating over `line`. – trutheality Jun 15 '11 at 19:40
  • 2
    Actually, a much simpler way to accomplish the same thing is `monstersToAdd.removeAll(line);` – trutheality Jun 15 '11 at 19:45
  • It will throw a CME -- however, a CME is not being thrown ;-) –  Jun 15 '11 at 22:37
  • Tried to self-answer to describe a new problem in detail (there's no room for it in the reply box). The system won't let me self-answer for another 4 hours, as new users must wait 8 hours after asking a question to answer themselves. However: I have pasted what I wanted to say here, if you'd be so kind to give it a read ;): http://pastebin.com/Ewk8ewZS Will write as a new answer too, when I can. Thank you for all of your help guys, really appreciate it :). – Mike Haye Jun 15 '11 at 23:09
  • @truth @pst @matt Oops, forgot to notify you :) – Mike Haye Jun 15 '11 at 23:10
  • 1
    @Mike: only the first @ notifies. you'll have to notify pst seperately. – trutheality Jun 15 '11 at 23:11
  • @Mike You can avoid that second problem simply by not adding the ones that have an id of `-1`. If you need more help with it, it would probably make sense to make that a new question and link this one as related (for context), although these are mostly independent things. – trutheality Jun 15 '11 at 23:27
  • Thanks for your input, truth, I will open a new question :). – Mike Haye Jun 16 '11 at 07:02
0

One possible problem is that you seem to be overwriting the same file when you "save". I suggest making a test run where you read from one file and write to the other.

In order to append to the file, you have a couple of options:

  1. Have your two functions share the 'RandomAccessFile`, that way after the first one is done reading the file, the cursor is at the end of the file and the second function can proceed to write from there, appending to the file
  2. Open a RandomAccessFile in the second function and move the cursor to the end of the file (for example by reading everything in it until there are no more lines) before writing.
trutheality
  • 23,114
  • 6
  • 54
  • 68