samuel
samuel

Reputation: 31

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 {
    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 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)

Upvotes: 3

Views: 15565

Answers (2)

fasseg
fasseg

Reputation: 17761

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

Upvotes: 5

amit kumar
amit kumar

Reputation: 21042

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

Upvotes: 1

Related Questions