开发者

Saving files with JFileChooser save dialog

I have a class that opens the files with this part:

JFileChooser chooser=new JFileChooser();
chooser.setCurrentDirectory(new File("."));
int r = chooser.showOpenDialog(ChatFrame.this);
if (r != JFileChooser.APPROVE_OPTION) return;
try {
    Logi开发者_JAVA技巧n.is.sendFile(chooser.getSelectedFile(), Login.username,label_1.getText());
} catch (RemoteException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

then I want to save this file in another file with:

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

but it only creates an empty file! what should I do to solve this problem? (I want my class to open all kind of files and save them)


here's your problem: in.read() only reads one byte from the Stream but youll have to scan through the whole Stream to actually copy the file:

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

or with a helper from apache-commons-io:

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


You have to read from in till the end of file. Currently you perform just one read. See for example: http://www.java-examples.com/read-file-using-fileinputstream

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜