Re: How to make my FileSaver being able to output any type stuff?
One more question: In the following program, I feel I am stuck with the
line:
printwriter = new PrintWriter(new
FileOutputStream(_fileChooser.getSelectedFile()));
Because the stuff I am saving maynot be text files. If it is other
things, then FileOutputStream should be replaced.
I cannot figure out more generic ways.
Thank you for your help.
<code>
public class FileSavingHelper {
private JFileChooser _fileChooser = null;
public FileSavingHelper()
{
_fileChooser = new JFileChooser(new File("."));
_fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
}
public PrintWriter getPrintWriter()
{
PrintWriter printwriter = null;
if (_fileChooser.showSaveDialog(null) ==
JFileChooser.APPROVE_OPTION) //user clicks Save button
{
//open the printwriter
try
{
printwriter = new PrintWriter(new
FileOutputStream(_fileChooser.getSelectedFile()));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " +
_fileChooser.getSelectedFile().getAbsolutePath());
}
}
else //user clicked Cancel button
{
System.out.println("Save command cancelled by user.");
}
return printwriter;
} //end of getPrintWriter
}
</code>
To use it:
PrintWriter pw = new FileSavingHelper().getPrintWriter();
pw.println("Hello");
pw.println("");
pw.println("This is Thursday");
pw.close();