tags:

views:

177

answers:

2

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)

A: 

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

Amit Kumar
thank you very much your helps were so useful
samuel
@samuel You can show your appreciation by voting up/accepting the answer(s).
Amit Kumar
+3  A: 

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];
while (in.read(buffer)>0){
    st.write(buffer);
}
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();
smeg4brains
thanks alot my friend you solvd my problems
samuel