使用非本地路径将图像保存到目录
我试图将用户选择的图像保存到我的资源包中。我只能通过给像“title.jpg”这样的简单路径或像“C://res/title.jpg”这样的完整本地路径来保存它。我怎样才能保存到一个包?使用非本地路径将图像保存到目录
public class ImportFile {
FileChooser fileChooser = new FileChooser();
String fileExtension;
BufferedImage bufferedImage;
File file;
public void chooseFile(){
extensionFilters();
file = fileChooser.showOpenDialog(null);
try{
bufferedImage = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
}
public void saveFile(BufferedImage importedFile, File file,String title) {
try{
File saved = new File("\res\"+title+findFileExtension(file));
ImageIO.write(importedFile,"jpg",saved);
}catch(IOException e){
e.printStackTrace();
}
}
private String findFileExtension(File file) {
String fileName = file.getName();
fileExtension = fileName.substring(fileName.lastIndexOf("."), fileName.length());
return fileExtension;
}
尝试做以下
File saved = new File(System.getProperty("user.dir") + "/src/<package name>/<filename>.jpg");
System.getProperty("user.dir")
:将给当前项目目录
<package name>
: “” 一定要更换在包名称中加上“/”
工作正常;谢谢一堆! – goobs14
是否要将图片上传到包中? 只是不给它一个路径,只是给一个名称,如使用file.getOriginalFilename()。
试试看?我希望它能帮助你。 代码: if(!file.isEmpty()){ try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename()))); out.write(file.getBytes()); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return"failure,"+e.getMessage(); } catch (IOException e) { e.printStackTrace(); return"failure,"+e.getMessage(); } return"success"; }else{ return"the file is empty"; }
你好..欢迎来到stackoverflow!如果你没有问题的具体答案,请使用下面的评论部分,否则你的答案将被其他成员投票。祝你好运 :) –
是否要保存到classpath中的包? –