我有一个用这部分打开文件的类:
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();
}
但它只会创建一个空文件!我应该怎么做才能解决这个问题? (我希望我的类(class)能够打开所有类型的文件并保存它们)
最佳答案
这是你的问题:in.read() 只从 Stream 中读取一个字节,但你必须扫描整个 Stream 才能真正复制文件:
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();
关于java - 使用 JFileChooser 保存对话框保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2381273/