//另存为菜单事件响应
MenuIt4.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
int result=JFile.showSaveDialog(Jf);
if(result==JFileChooser.APPROVE_OPTION)
{ FileInputStream fis=null;
FileOutputStream fos=null;
//获取文件列表输入的文件
File fi=JFile.getSelectedFile();
String f=fi.getAbsolutePath()+"\\text.txt";

try
{
fis=new FileInputStream(Jtp.getText());
fos=new FileOutputStream(f);

byte[] bytebuffer=new byte[32];
int hasRead=0;
while((hasRead=fis.read(bytebuffer))>0)
{
fos.write(bytebuffer,0,hasRead);
}

catch(FileNotFoundException e)
{
e.printStackTrace();

catch (IOException e) {

e.printStackTrace();
}
finally
{
if(fis!=null)
{try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}

}
if(fos!=null)
{
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
);


上面的JTP获取的是JTextPane面板上的内容。当单击保存时报错,提示找不到文件。系统提示找不到的文件是我在JtextPane上输入的内容,它把这个内容当成文件名了,无视了JFileChooser上面输入的文件名。我输入流,输出流没弄反把?java

解决方案 »

  1.   

    save_as.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    JFileChooser jc = new JFileChooser();
    int var = jc.showSaveDialog(jframe);
    if(var == JFileChooser.APPROVE_OPTION){
    File dir = jc.getCurrentDirectory();  // 返回当前的目录路径
    File file = jc.getSelectedFile();   // 获得选中的文件
    write(new File(dir,file.getName()),textArea.getText());
    }
    } private void write(File file, String text) {
    try {
    PrintWriter write = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
    write.println(text);
    write.close();
    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    }
    }
    });