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.

6
  • "not sorting anything away" - I don't see any actual code in here that performs a sort. Commented Jun 15, 2011 at 19:33
  • @Matt Ball "filtering" -- That's why there is no CME ;) Commented Jun 15, 2011 at 19:34
  • 2
    It is recommended to write List<String> x = new ArrayList<String>() instead of ArrayList<String> y = new ArrayList<String>() code to the iterface, not the implementation. :) Commented Jun 15, 2011 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. Commented Jun 15, 2011 at 19:39
  • @Mike: It would. pst is worried about the end-of-line character, but the API is pretty clear about discarding them. You can always call trim to really make sure there's no extra whitespace. Commented Jun 15, 2011 at 19:54

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

10 Comments

@trutheality Note that monstersToAdd is being iterated in the loop it is (potentially) modified inside. The contains (or line) is not relevant.
@truth: look at the code again. monster is removed from the collection that is being iterated.
@pst oh, for some reason I thought it was iterating over line.
Actually, a much simpler way to accomplish the same thing is monstersToAdd.removeAll(line);
@Mike: only the first @ notifies. you'll have to notify pst seperately.
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.