2012-02-05 37 views
1

我遵循this tutorial在我的JSF2應用程序中上傳文件。 該應用程序工作正常,但我不滿意的一個方面。 重建請求時,通過請求發送的文件保存在磁盤上的某處。如何移動/重命名上傳的文件?

即使文件已保存,我需要用輸入包含操作方法的受管Bean後可用的名稱重命名該文件。

因此,我決定創建一個名稱爲de的新文件,複製已保存的文件,然後刪除不需要的文件。

private File uploadFile; 
//... 
try { 
    BufferedWriter bw = new BufferedWriter(new FileWriter(newFile)); 
    BufferedReader br = new BufferedReader(new FileReader(uploadFile)); 

    String line = ""; 
    while ((line = br.readLine()) != null){ 
     bw.write(line); 
    } 
} catch (Exception e){} 

新的文件出現在所需位置,但引發此錯誤,當我試圖打開文件:「無效或不支持PNG文件」

這是我的問題:

  1. 有沒有更好的方法來解決這個問題?
  2. 此解決方案是上傳圖片的最佳方式嗎?是否有理由在可能需要調整圖片大小或所需名稱尚不可用時在業務邏輯之前保存文件。

LE: 我知道ABOT this tutorial很好,但我想這樣做鑽嘴魚科只。

回答

2

當您處理二進制文件(如圖像)時,請勿使用ReaderWriter。使用流:FileInputStreamFileOutputStream。最好的變體是使用@Perception解決方案,方法爲renameTo

讀者讀取文件就好像它包含字符(例如txt,properties,yaml文件)。圖像文件不是字符,它們是二進制的,你必須使用流。

3

java.io.File對象中已經有一個重命名方法,如果它不適合您的情況,我會很驚訝。

 
public boolean renameTo(File dest) 

    Renames the file denoted by this abstract pathname. 

    Many aspects of the behavior of this method are inherently platform-dependent: 
    The rename operation might not be able to move a file from one filesystem to 
    another, it might not be atomic, and it might not succeed if a file with the 
    destination abstract pathname already exists. The return value should always 
    be checked to make sure that the rename operation was successful. 

你也可以檢查文件是否在保存之前存在,並且可以使用ImageIO類保存執行初始前做對上傳的文件驗證。