The new forums will be named Coin Return (based on the most recent vote)! You can check on the status and timeline of the transition to the new forums here.
The Guiding Principles and New Rules document is now in effect.

Java Help (I/O)

YallYall Registered User regular
Hey gang,

I'm trying to re-learn java (very limited experience) and I'm playing around in Eclipse.

The problem I'm having relates to I/O;

I have a for loop in my "main" and during each iteration I'm trying to call a class to write a line to an output file. I've created a class called fileWrite, that I pass the string I'd like to write to the output file:

class fileWrite
{
public void writeTextFile(String output)
{
try{

FileWriter fstream = new FileWriter("c://users//Dave//workspace/output.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(output);
out.newLine();
out.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}

But as you can see, every time I call the class the output file is being recreated rather than opened and having a new line written to the file. Any thoughts on how I might be able to resolve this? I tried creating the FileWriter object in my main and change the class to accept it as an input argument and remove the "new FileWriter" line from the class, but the loop seems to think that the variable isn't declared.

I'm sure I'm missing something simple, but like I said, in Java terms I'm a novice (grew up on C++ and Turbo Pascal) and I haven't written any significant code in a long time.

Thanks in advance.

Posts

  • kimekime Queen of Blades Registered User regular
    I hate I/O

    Anyways, according to this site, it should be a simple fix. Add a second parameter "true" to your FileWriter declaration.

    I'm not 100% sure if this is an issue or not, but your file name is maybe incorrect? There's only one slash before output. I'm assuming you aren't having trouble accessing the file though, so I guess that's not causing any important problems.


    (You can see in the Java documentation for FileWriter the specifics of the parameters you have the option of including. The documentation and Google should always be go-to resources :) )

    Battle.net ID: kime#1822
    3DS Friend Code: 3110-5393-4113
    Steam profile
  • YallYall Registered User regular
    Thanks. Going back to turbo pascal and c++ I've always hated I/o. Nice to know I'm not alone.:)

Sign In or Register to comment.