问题描述
我想将文件上传到本地文件夹(在我的PC上)。用户应选择一个文件。比该文件应加载到一个文件夹中(此文件夹在我的Java类中进行了硬编码)。不幸的是,我没有找到一个好的解决方案。
我刚刚发现了一个关于JFileChooser
的东西,很高兴打开一个文件,但不加载它。
public static void main(String[] args){
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images","jpg","gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
}
是否可以仅使文件选择器访问特定文件夹?文件夹是这样硬编码的:
public static String uploadPath = System.getProperty("user.dir") + "/uploads Modul1";
解决方法
复制或移动文件与选择文件的方式无关。复制文件的简单方法是使用Files.copy
method。将其添加到现有代码中的方法如下:
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
System.out.println("You chose to copy this file: " +
selectedFile.getName());
Path newPath = Paths.get(uploadPath,selectedFile.getName());
Files.copy(selectedFile.toPath(),newPath);
}
官方教程中有关于复制文件的部分:https://docs.oracle.com/javase/tutorial/essential/io/copy.html
如果要移动而不是复制文件,请使用Files.move
而不是Files.copy
。