Tuesday, 13 September 2011

Java: Writing to a File

    Yesterdays reading from a file, I mentioned you needed the full file path to read from the program. This doesn't appear to be true if your file is located in the parent directory of your code. Let me know if you find something different, but if you have a project folder named "Testing" and within it, the code to run it is within a folder named "src" (Using Netbeans as my eternal example. It automatically does this.), and your info file if located in "Testing/InfoFile.txt", you can simply call readFile( "InfoFile.txt" ).

    You live, you learn. So let's add to our program now. We should have 2 more functions to write. writeFile, and appendFile. Writing to a file is all well and good, but it overwrites previously found data. This is fine in some cases, but a lot of the time you want to add more data to what's present in the file. Nobody wants to read a file, save each line to a variable, then write it all back in, so that's where appending comes in.

    Ta-da! I think I like using these images. It saves time typing it all out again, and has the color coding of the IDE, so it's more eye-catching, don't you think? Anyway, time to throw in the appendFile so we'll be able to comfortably test everything. The code itself looks fairly straightforward. Call the writer, call the buffered writer for efficiency, write what you want, then close the file. Good times.

    Again, the code is straightforward, pretty much the same thing, except when calling the FileWriter, a second parameter (a boolean) is required to be true. This lets the class know you want to append and not overwrite. Seems simple, but let's test it to make sure. Though, in hindsight it probably would have been better to test writing first so we could read after to verify success. Anyway!

    Everything (should be) is working great, and I'm done with my coding for the night.
    Edit: It occurs to me I should probably use shorter lines if I'm to use screencaps in the future.

    That's it for tonight. Questions or comments? Leave them in the comment section below. Follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here, and feel free to throw loads of criticism at us. 


  1. i'm learning a different kind of code right now, the tax code.

  2. At your response on my page - lol!