I have a program that writes data to a file as part of its functionality, however the way it is programmed means it can only write one String and i wish for it to be able to write more than this; a sentence for example. I would like to know how i can achieve this, any help guys?
Firstly (as the code is at the moment), in the main method, the user is asked if they would like to write data to the file (the path to which in this particular case is stored in the "path" parameter) and if the answer is equal to "yes" then the data is written by the code in the relevant section of the If statement that can be seen in the code below:
System.out.println("\nWould you like to write data to the file? (yes\\no)\n");
answer1 = in.next();
answer = "yes";
answer = "no";
System.out.println("\nEnter data to write to ADS:\n");
answer2 = in.next();
System.out.println("\nNo data was written to the ADS\n");
The code that does the writing is in a class called writeToFile and can be seen below:
public class writeToFile
public static void write(String path, String answer3)
FileOutputStream out = new FileOutputStream(path);
System.out.println("\nData was written to file\n");
System.out.println("Exception has been thrown :" + e);
So how can this be modified to write a few Strings to the file and not just one? example code would be brilliant, as i haven't much time to get this modification done.
FileOutputStream has a constructor, that allows you to designate if the data is added to the files existing content, or if it replaces all. I propose you give that method of your a boolean param, and use that in the FileOutPutStreams constructor.
However, there is not necessarily lot of sense in writing stuff piecemeal to a File. So what your writeToFile class could provide, is a dummy context, in which these bits and pieces are stored, when all expected data is in, write all that to the actual file. Simplest way this can be done simply providing a StringWriter instance. You can append as many String to it as you like, and the call your file writing method using the StringWriters toString() as data.
Last edited by Londbrok; June 11th, 2009 at 02:13 AM.