java 使用 JFileChooser 保存对话框保存文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2381273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 20:53:27  来源:igfitidea点击:

Saving files with JFileChooser save dialog

javaswing

提问by samuel

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)

但它只会创建一个空文件!我该怎么做才能解决这个问题?(我想让我的班级打开所有类型的文件并保存它们)

回答by fasseg

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:

这是您的问题: in.read() 仅从流中读取一个字节,但您必须扫描整个流才能实际复制文件:

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:

或使用apache-commons-io的助手:

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

回答by amit

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

您必须从in文件末尾读取。目前您只执行一次读取。参见例如:http: //www.java-examples.com/read-file-using-fileinputstream