2010-03-04 82 views
3

我有一個與該部分打開的文件類:保存文件用的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

回答

5

這裏是你的問題: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