创建新文件与createTempFile

时间:2014-03-11 21:48:35

标签: java android file

我想创建一个文件并将URI设置为我的imageView,如下所示:

// this code will work, but it will generate a random number at the end of my file
f = File.createTempFile(image, JPEG_FILE_SUFFIX, getAlbumDir());

// this will result with an exception at imageView.setImageURI()
f = new File(getAlbumDir(), image + JPEG_FILE_SUFFIX);

imageView.setImageURI(Uri.fromFile(f));

这是例外:

01-02 15:19:06.575: W/ImageView(26097): Unable to open content: file:///storage/sdcard0/dcim/myapp/20000102_151858_.jpg
01-02 15:19:06.575: W/ImageView(26097): java.io.FileNotFoundException: /storage/sdcard0/dcim/myapp/20000102_151858_.jpg: open failed: ENOENT (No such file or directory)

因为我想摆脱我的图像名称末尾的随机数。如何让new File()工作?

1 个答案:

答案 0 :(得分:1)

  

如何使新的File()有效?

它确实有效,但它不会在辅助存储上创建文件。它只是在内存中创建一个File对象。所以,在第二种情况下,你根本没有创建一个文件。

如果要创建空文件,请致电f.createNewFile()。您可能不想这样做:您可能希望通过new FileOutputStream(f).

将一些内容添加到其中