Saving Files Using the JFileChooser Save Dialog

I have a class that opens 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 {
    Login.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 using

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 files and save them)

+3
source share
2 answers

here is your problem: in.read () only reads one byte from Stream, but you have to scan the entire 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 an assistant from apache-commons-io :

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

Source: https://habr.com/ru/post/1735451/


All Articles