Java 使用JFileChooser保存对话框保存文件

Java 使用JFileChooser保存对话框保存文件,java,swing,Java,Swing,我有一个类可以打开包含此部分的文件: JFileChooser chooser=new JFileChooser(); chooser.setCurrentDirectory(new File(".")); int r = chooser.showOpenDialog(ChatFrame.this); if (r != JFileChooser.APPROVE_OPTION) return; try { Login.is.sendFile(chooser.getSelectedFile(

我有一个类可以打开包含此部分的文件:

JFileChooser chooser=new JFileChooser();
chooser.setCurrentDirectory(new File("."));
int r = chooser.showOpenDialog(ChatFrame.this);
if (r != JFileChooser.APPROVE_OPTION) return;
try {
    Login.is.sendFile(chooser.getSelectedFile(), Login.username,label_1.getText());
} catch (RemoteException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
然后,我想将此文件保存到另一个文件中:

JFileChooser jfc = new JFileChooser();
int result = jfc.showSaveDialog(this);
if (result == JFileChooser.CANCEL_OPTION)
    return;
File file = jfc.getSelectedFile();
InputStream in;
try {
    in = new FileInputStream(f);

    OutputStream st=new FileOutputStream(jfc.getSelectedFile());
    st.write(in.read());
    st.close();
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}


但它只会创建一个空文件!我该怎么解决这个问题?(我想让我的班级打开所有类型的文件并保存它们)

你必须从中的
一直读到文件结束。目前您只执行一次读取。请参阅示例:

这是您的问题:in.read()只从流中读取一个字节,但您必须扫描整个流才能真正复制文件:

OutputStream st=new FileOutputStream(jfc.getSelectedFile());
byte[] buffer=new byte[1024];
int bytesRead=0;
while ((bytesRead=in.read(buffer))>0){
    st.write(buffer,bytesRead,0);
}
st.flush();
in.close();
st.close();
或与以下人员的助手一起:


建议:您还应在
@samuel中关闭
文件输入流。您可以通过投票/接受答案来表示感谢。
OutputStream st=new FileOutputStream(jfc.getSelectedFile());
IOUtils.copy(in,st);
in.close();
st.close();