PDA

Click to See Complete Forum and Search --> : Help with files


nievesj
Dec 3rd, 2000, 02:50 PM
Hi!, Can someone please explain to me how i can write the contains of a TextField into a file...
I tried this, but is not working...

try
{
output_stream =new DataOutputStream(new DataOutputStream
(new BufferedOutputStream
(new FileOutputStream("c:\\data.txt"))));
Data=textfield.getText();
output_stream.writeChars(Data);
output_stream.close();
}//try
catch(IOException e){}

I checked the file and its empty :(

Thanks in advance!

Dec 3rd, 2000, 08:58 PM
When do you attempt the try block? Also, a second new DataOuputStream was excessive although it works with the redundant one which I omitted here. I'm attempting the try block after I hit the Ok button. Run this code, put text in the textfield, hit the Ok button, then check the file. You can also close the app/window with the X.

I'm sure there are better ways to write strings.

//Test.java
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class Test extends Frame{
public Test(){
final TextField textfield = new TextField();
add(textfield);
Button b = new Button("Ok");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){

try
{
DataOutputStream output_stream =new DataOutputStream(new BufferedOutputStream
(new FileOutputStream("c:\\data.txt")));
String Data=textfield.getText();
output_stream.writeChars(Data);
output_stream.close();
}//try
catch(IOException e){}

System.out.println("Pressed Ok Button");
}
});
add(b, BorderLayout.SOUTH);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.out.println("Pressed X");
System.exit(0);
}
});

pack();
show();
}
public static void main(String[] args){
new Test();
}
}

Dec 3rd, 2000, 09:07 PM
And see
http://java.sun.com/docs/books/tutorial/essential/io/filestreams.html