Search code examples
javafilewriterwriter

Java writes writes line multiple times?


static void goOut(String in) {
                  //instance variables
    String fileCopy = currentLine +     in;
    try {
        FileWriter writer = new FileWriter(output,true);


        writer.write(line1 + System.getProperty("line.separator", "\r\n"));
        writer.write(fileCopy + System.getProperty("line.separator", "\r\n"));


    }   catch(IOException ex) {
        ex.printStackTrace();
    }
}

Edited code to the correct standard as pointed out by other users.


Solution

  • of course because thats what you r telling it to do. every time is called it writes both x and the number. a quick fix: you can keep a flag if it is the first run set it flag = true. and check within ur method, sth like this:

    public class YourClass{
    
    private boolean didRun = false;
    
    static void goOut(String in) {
    
        ...... init ur file and writer
        if(!didRun)
           writer.write(Y);
    
         writer.write(in);
         writer.close();
         didRun = true;
        }
    }
    

    I dont know the rest of the code but i think thats what u need