保存文件用的JFileChooser保存对话框

问题描述:

我有一个与该部分打开的文件类:保存文件用的JFileChooser保存对话框

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(); 
} 

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

+1

一个建议:你也应该关闭'FileInputStream in'。 – 2010-03-04 17:25:12

您必须从in读取直到文件结束。目前您只执行一次阅读。例如见:http://www.java-examples.com/read-file-using-fileinputstream

+0

非常感谢你的帮助非常有用 – samuel 2010-03-04 18:38:29

+0

@samuel你可以通过投票/接受答案来表达你的赞赏。 – 2010-03-04 19:06:59

这里是你的问题: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(); 

或用助手从apache-commons-io

OutputStream st=new FileOutputStream(jfc.getSelectedFile()); 
IOUtils.copy(in,st); 
in.close(); 
st.close(); 
+0

非常感谢我的朋友解决了我的问题 – samuel 2010-03-04 18:37:56