2017-06-20 106 views
0

我試圖將用戶選擇的圖像保存到我的資源包中。我只能通過給像「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; 
    } 
+0

是否要保存到classpath中的包? –

回答

0

嘗試做以下

File saved = new File(System.getProperty("user.dir") + "/src/<package name>/<filename>.jpg");

System.getProperty("user.dir"):將給當前項目目錄

<package name>: 「」 一定要更換在包名稱中加上「/」

+0

工作正常;謝謝一堆! – goobs14

0

是否要將圖片上傳到包中? 只是不給它一個路徑,只是給一個名稱,如使用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"; }

+0

你好..歡迎來到stackoverflow!如果你沒有問題的具體答案,請使用下面的評論部分,否則你的答案將被其他成員投票。祝你好運 :) –

相關問題