Code:SimpleWriter
From CompWiki
Simple Writer
I think there are any number of similar Classes available on the internet; we keep this one really, really simple:
import java.io.*;
/**
* Class to write simple text files
*
* @author Mr J
* @version 1.0
*/
public class SimpleWriter
{
private PrintWriter outFile;
public SimpleWriter(String fileName) throws IOException
{
outFile = new PrintWriter(new FileWriter(fileName));
}
public void writeLine(String line)
{
outFile.println(line);
}
public void close(){ outFile.close(); }
}
To use the code, we would do something like this:
private static final String FILENAME = "c:\\MyFiles\\data.txt;"
We use two slashes because one \ is an escape character - it puts a special character in a String (like \n - new line or \t - tab or \" to put a quote inside a String). So \\ puts a single \ inside a String.
Example method to save data:
/**
* Save array contents to a text file
*/
private void saveToFile()
{
try
{
SimpleWriter writer = new SimpleWriter(FILENAME);
for(int x = 0; x < ARRAY_ITEMS; x++)
{
writer.writeLine(array[x].toString());
}
writer.close();
}
catch(IOException io)
{
messages.setText("Some error writing to file");
System.exit(1);
}
}
You will need to control ARRAY_ITEMS - the end of the list of items to be written.
You may also need to supply a toString() method depending upon what is actually inside the array. If it is an array of String already, you won't need to.
If you don't close the file you may not find your file contains anything. Because your program can process items faster than they can be written to file, a buffer (an area of memory for temporary storage), is used to hold data waiting to be written to the file. close() makes sure this buffer contents are "emptied" into the file.
Further ideas writing text files:
- You could add validation code to check that the filename is valid - look up the rules on your own operating system.
- You could look at the range of IOExceptions that can be generated and deal with each one seperately to give more detailed information back to your user.
- You can output data - eg from asimulation program - as a csv file (comma separated variables) that can be read by another application such as a spreadsheet or word processor - the user can then produce graphs or tables of results if they wish. Of course, only your Java code contributes to the dossier (not, for example, any Excel macros).
Such an approach gets you out of attempting to create graphs yourself using Java libraries (a complex process which may involve a lot of work for which there is little credit for you in IB Dossier terms).
- You could investigate whether the PrintWriter Class has any other methods you could use besides printLine() and close(). Try the | JDK Documentation set.

