Java 将文件对象写入另一个位置
我选择了使用Java 将文件对象写入另一个位置,java,swing,Java,Swing,我选择了使用 File file = fileChooser.getSelectedFile(); 现在,当用户单击“保存”按钮时,我想将用户选择的文件写入另一个位置。如何使用swing实现这一点?swing只会为您提供位置/文件对象。您必须自己编写新文件 要复制文件,我将向您指出这个问题:Swing将只提供位置/文件对象。您必须自己编写新文件 要复制文件,我将向您指出这个问题:将文件读入InputStream,然后将其写入OutputStream。将文件读入InputStream,然后将其写
File file = fileChooser.getSelectedFile();
现在,当用户单击“保存”按钮时,我想将用户选择的文件写入另一个位置。如何使用swing实现这一点?swing只会为您提供位置/文件对象。您必须自己编写新文件
要复制文件,我将向您指出这个问题:Swing将只提供位置/文件对象。您必须自己编写新文件
要复制文件,我将向您指出这个问题:将文件读入InputStream,然后将其写入OutputStream。将文件读入InputStream,然后将其写入OutputStream。如果您使用的是JDK 1.7,则可以使用提供多种复制方法的类将文件复制到给定的destiny。如果您使用的是JDK1.7您可以使用提供多种复制方法的类将文件复制到给定的destiny。选择您需要的文件,例如
JFileChooser open = new JFileChooser();
open.showOpenDialog(this);
selected = open.getSelectedFile().getAbsolutePath(); //selected is a String
…为了保存副本
JFileChooser save = new JFileChooser();
save.showSaveDialog(this);
save.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
tosave = fileChooser.getSelectedFile().getAbsolutePath(); //tosave is a String
new CopyFile(selected,tosave);
…copyFile类将类似于
public class CopyFile {
public CopyFile(String srFile, String dtFile) {
try {
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
还可以看看这个问题:MightBeHelpfull选择您需要的文件,例如
JFileChooser open = new JFileChooser();
open.showOpenDialog(this);
selected = open.getSelectedFile().getAbsolutePath(); //selected is a String
…为了保存副本
JFileChooser save = new JFileChooser();
save.showSaveDialog(this);
save.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
tosave = fileChooser.getSelectedFile().getAbsolutePath(); //tosave is a String
new CopyFile(selected,tosave);
…copyFile类将类似于
public class CopyFile {
public CopyFile(String srFile, String dtFile) {
try {
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
还有一个问题:MightBeHelpfullSwing不能为您做任何事情,因为Swing只处理UI,不处理文件操作。但是,您可以自己将所选文件中的字节复制到目标文件中,也可以使用ApacheCommons io中的FileUtils:而Swing不能为您做任何事情,因为Swing只处理UI,不处理文件操作。但是,您可以自己将所选文件中的字节复制到目标文件中,也可以使用apachecommons io:and中的FileUtils