Sorry about this

Discussion in 'Plugin Development' started by RightLegRed, Jan 21, 2011.

Thread Status:
Not open for further replies.
  1. Offline

    Archelaus

    I know this doesn't pertain to Bukkit API. But I was wondering how to write lines to a file without erasing the already there text. I'm relatively new to Java, thanks.
     
  2. Offline

    Meta1203

    How would you normally write to a file? I know that you can just dump all the file's information to a string/array, edit what you need to, then dump it back to the file. This would be my method of choice, as it only writes to the file twice!
     
  3. Offline

    Mixcoatl

    You could use code like this:
    Code:
    FileOutputStream out = null;
    PrintStream printer = null;
    try {
        // The 'true' means append to the file.
        out = new FileOutputStream(filename, true);
    
        // We need to wrap the FileOutputStream in
        // a PrintStream to print text to a file.
        // The 'true' means to flush automatically.
        printer = new PrintStream(out, true);
    
        // Print stuff to the file.
        printer.println("Hello, world!");
    } catch (IOException ex) {
        // Handle IO errors here.
    } finally {
        // Closing the print stream takes some work.
        try {
            if (printer != null) printer.close();
        } catch (IOException ex) {
            // Ignore or log a warning message.
        }
        // Closing the output stream takes some work.
        try {
            if (out != null) out.close();
        } catch (IOException ex) {
            // Ignore or log a warning message.
        }
    }
     
  4. Offline

    mjmr89

    Get the File object of what you want to write, create a writer from it (Writer w = new FileWriter(yourFile)). Use w.append("TextHere"). Don't forget to use w.close() after you're done :). Pretty sure this will do it.
     
  5. Offline

    Mixcoatl

    Regarding the FileWriter class:
    Code:
    // Need to pass true to append to a file.
    FileWriter w = new FileWriter(filename, true);
    The FileWriter class provides methods for writing string and character data. To write more interesting information to your file, you might prefer to wrap your FileWriter in an instance of the PrintWriter class. Ultimately, PrintWriter is to FileWriter what PrintStream is to FileOutputStream.
     
Thread Status:
Not open for further replies.

Share This Page