Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

java - What is the best way to create temporary files on Android?

Well, this is not exactly a question, as I'm not really "stuck" on my code, but I've found some strange behavior for Android API regarding accessing the external storage and the File.createTempFile() method, and I'd like to understand what's happening...

Please note that my manifest does not include the <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">.


Part 1 :

I have the following code which does work as a charm :

File tempFile = new File(Environment.getExternalStorageDirectory(),
                      "my_temp_file.png");

it creates a temporary file for me, and I can write datas in it without any trouble.

Question 1 : Why does it work, as I'm not supposed to have writing rights on my SDCard ?


Part 2 :

I've tried to change my code to use the createTempFile which is the official method to create temporary file. So I've tried :

File tempFile = File.createTempFile("my_temp", "png", 
                      Environment.getExternalStorageDirectory());

and added the WRITE_EXTERNAL_STORAGE in my manifest.xml. Guess what ? This does not work, and I get a java.io.IOException :

09-07 14:07:29.061: E/_CLOG(19982): java.io.IOException: Permission denied
09-07 14:07:29.061: E/_CLOG(19982):     at java.io.File.createNewFileImpl(Native Method)
09-07 14:07:29.061: E/_CLOG(19982):     at java.io.File.createNewFile(File.java:1257)
09-07 14:07:29.061: E/_CLOG(19982):     at java.io.File.createTempFile(File.java:1322)
09-07 14:07:29.061: E/_CLOG(19982):     at com.(...).onClick(ProfileImageUpdater.java:58)

Question 2 : Why this doesn't work, whereas imho it should ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

try like this...

File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("prefix", "extension", outputDir);

Edit :

for Question 2

It may be issue as below link...

Environment.getExternalStorageDirectory does not return the path to the removable storage


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...