Problems with PrintWriter
Hi,
I have wrote a little program to test appending user input to a text file. For some reason the text isn't written to the file when I click the 'Append' button (whether I use .append() or .println()).
I don't get why because the text is being retrieved from the textfield (I tested that) and the PrintWriter is not null. Here is the code:
protected JTextField textField;
protected JButton read, stop;
String text =null;
PrintWriter outputStream =null;
File outFile =null;
public showTxtF2(){
super(new GridBagLayout());
textField =new JTextField(20);
//textField.addActionListener(this);
read =new JButton("Append");
read.addActionListener(this);
stop =new JButton("Stop");
stop.addActionListener(this);
//Add Components to this panel.
GridBagConstraints c =new GridBagConstraints();
c.gridwidth = GridBagConstraints.RELATIVE;
c.fill = GridBagConstraints.HORIZONTAL;
add(textField, c);
c.gridwidth = GridBagConstraints.REMAINDER;
add(read, c);
add(stop, c);
outFile =new File("testText2.txt");
try{
outputStream =new PrintWriter(new FileWriter(outFile));
}catch (FileNotFoundException exp){
System.out.println("WARNING: Error writing to command file");
return;
}
catch (IOException exp){
System.out.println("WARNING: Error writing to command file");
return;
}
}
publicvoid actionPerformed(ActionEvent e){
//
JButton source = (JButton)(e.getSource());
String cmdinfo = source.getText();
if (cmdinfo.equals("Stop")){
if (outputStream !=null){
outputStream.close();
}
return;
}
if (cmdinfo.equals("Append")){
String text = textField.getText();
if (outputStream !=null){
outputStream.append(text);
}else{
System.out.println("Couldn't write to file");
}
}
}
.....
Most grateful for any input as to why...
[3937 byte] By [
msparka] at [2007-11-27 10:38:19]

Have you searched your computer to see if you have a new version of "testText2.txt" located somewhere on your disk? You may have created a new version of this file without realizing it. Also, do you ever flush your output stream?
Also, if you do find your file, I think that you will find that printwriter is not actually appending as you are expecting. The first thing printwriter does is zero out the file (I believe).
Would any of this be helpful? To append text to a text file, I think that you have to use a FileWriter object that is constructed with the first parameter a File object and the second parameter a boolean true expression.
Here's an example (anyone, please correct any errors found):
import java.io.*;
import java.util.Scanner;
/**
* tests appending character output to an already existing text file
* uses PrintWriter wrapping a BufferedWriter wrapping a FileWriter.
* By constructing the FileWriter with a "true" boolean parameter, I am
* telling it to append text to an existing file.
*
* Also uses System.getProperty("line.separator") to get the line separator
* for whatever system I happen to be on.
* @author Pete
*
*/
public class TestPrintWriter
{
private PrintWriter out = null;
private File outFile = null;
private String fileName = "testPrintWriter.txt";
private String inputText = "";
private String eol = System.getProperty("line.separator");
public void initOutputStream()
{
outFile = new File(fileName);
try
{
// new FileWriter(outFile, true) tells java that I want to append text
// to the file referenced by outFile
out = new PrintWriter(new BufferedWriter(new FileWriter(outFile, true)));
}
catch (FileNotFoundException exp)
{
System.out.println("WARNING: Error writing to command file");
return;
}
catch (IOException exp)
{
System.out.println("WARNING: Error writing to command file");
return;
}
}
private void getInputText()
{
System.out.print("Enter text to send to file (\"quit\" to exit): ");
String s = "";
Scanner sc = new Scanner(System.in);
while (!s.equalsIgnoreCase("quit"))
{
s = sc.nextLine();
if (!s.equalsIgnoreCase("quit"))
{
inputText += s + eol;
}
}
sc.close();
}
private void writeToFile()
{
if (out != null)
{
if (inputText != null && !inputText.isEmpty())
{
out.print(inputText);
out.flush(); // I think I don't need this since I call "close()"
}
out.close();
}
}
public static void main(String[] args)
{
TestPrintWriter tpw = new TestPrintWriter();
tpw.initOutputStream();
tpw.getInputText();
tpw.writeToFile();
}
}
Message was edited by:
petes1234
> Have you searched your computer to see if you have a
> new version of "testText2.txt" located somewhere on
> your disk? You may have created a new version of
> this file without realizing it. Also, do you ever
> flush your output stream?
Thanks for the replies! Sorry i didn't realise I had, any, I didn't get the email notification for some reason.
I'm sure I have the right file. No I never flush the stream. When would I need to?
I haven't had a look yet at the code you've given me, thanks very much, I'll have a look now.
> Thanks for the replies! Sorry i didn't realise I had,
> any, I didn't get the email notification for some
> reason.
No problem, and you're entirely welcome.
> I'm sure I have the right file. No I never flush the
> stream. When would I need to?
Look at my example regarding flushing the stream. I think if you close files up, you probably don't need to flush, but I'm not 100% sure on this. Also, please do me a favor and search your disk for files named the same as the filename you write to in your code. You MAY have another copy lurking somewhere, and it can't hurt to search.
> I haven't had a look yet at the code you've given me,
> thanks very much, I'll have a look now.
Good luck.
> * Also uses System.getProperty("line.separator") to
> get the line separator
Just a small side note about this: it's better to let the Scanner class decide what the line separator is. If you define your own line separator like that on Windows and are opening a text file created on a *nix OS, you will get on big chunk of text. The Scanner class is "smart" enough to figure out which line separator to choose.
Edit:
Oh ****, I should read it properly first: you're writing to a file!
My bad.
You'd be better off using a FileWriter which has a constructor that takes a boolean parameter which allows you to append to a file.
> You'd be better off using a FileWriter which has a
> constructor that takes a boolean parameter which
> allows you to append to a file.
Flounder:
In my code example above, does this make sense?:
out = new PrintWriter(new BufferedWriter(new FileWriter(outFile, true)));
and if not, what would you use instead? Thanks
When I do File IO I use a BufferedWriter wrapped around a FileWriter and not use the PrintWriter. It works for me and I have never had problems.
P.S. My comments in above reply were directed at OP and not you.
Message was edited by:
flounder
> When I do File IO I use a BufferedWriter wrapped
> around a FileWriter and not use the PrintWriter. It
> works for me and I have never had problems.
>
> P.S. My comments in above reply were directed at OP
> and not you.
It doesn't matter to me who your comments were directed at, as long as I can learn a thing or two. Again, thanks for your thoughts.