我一直试图在Netbeans上的Java中使用JFileChooser保存TextField的数据。这就是我到现在为止所做的:
private void Cmd_saveActionPerformed(java.awt.event.ActionEvent evt)
{
int p = jOptionPane3.showConfirmDialog(null,
"Do you want to save this","Save",JOptionPane.YES_NO_OPTION );
if (p == JOptionPane.YES_OPTION)
{
JFileChooser chooser = new JFileChooser();
chooser.showSaveDialog(null);
}
}
这只是一个例子,你可以做不同的:
//imports
public class FileChooser extends JFrame
{
private JFileChooser fileChooser = null;
private JTextField name_textField = null;
private JLabel name_label = null;
private JButton save_text = null;
public FileChooser()
{
setLayout(new FlowLayout());
name_label = new JLabel("Enter your name");
name_textField = new JTextField(15);
save_text = new JButton("Save your name to a file!");
save_text.addActionListener(new Name_ActionListener());
add(name_label);
add(name_textField);
add(save_text);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
setLocationRelativeTo(null);
}
private class Name_ActionListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
int answer = JOptionPane.showConfirmDialog(null,
"Do you really want to save the your name?",
"Save", JOptionPane.YES_NO_OPTION);
if(answer == JOptionPane.YES_OPTION)
{
fileChooser = new JFileChooser();
fileChooser.showSaveDialog(null);
// This is a reference which allows you to save a FileOutputStream object
OutputStream out = null;
// File is a class which represents the physical file
// Creating a file with which represents the physical file
// with the absolute path chosen by the user using fileChooser
File file = new File(fileChooser.getSelectedFile().getAbsolutePath());
try
{
//You can use other classes to store data on the file like Formatter
out = new FileOutputStream(file);
for(byte b : name_textField.getText().getBytes())
out.write(b);
}
catch(IOException e1)
{
e1.printStackTrace();
}
finally
{
if(out != null)
{
try
{
out.close();
out = null;
}
catch(IOException e2)
{
e2.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args)
{
FileChooser fileChooser = new FileChooser();
}
}
还可以查看有关FileOutputStream和类似类的文档,以更好地理解如何在Java中管理文件。