2012-02-05 87 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类保存执行初始前做对上传的文件验证。