简体   繁体   中英

Writing on SDCard Problem - Android

I'm trying to write a file to my SDcard in my HTC Hero phone. I create the File in my SDCard using:

File = new File(path.getAbsolutePath(), "Filename.txt");

where path is the path to my externalStorageDirectory (ie \\sdcard)

When I log the path of this file, it does say \\sdcard\\filename.txt

However, when I create a fileoutputstream to write to the file, suddenly the filepath is changed to \\data\\data and I cannot access it.

Can someone please help clarify how I can create a File in the SDCard and then write to it?

Thanks!

Edit:

path = Environment.getExternalStorageDirectory();
Log.d("SDCARDPLSWORK", path.toString());
    try
    {
        myFile = new File(path.getAbsolutePath(), "SensorValues.txt");
        boolean i = myFile.createNewFile();
        Log.d("SDCARDPLSWORK", myFile.toString() + " " + i);
        fos = new FileOutputStream(myFile);
        Log.d("FILEANDROID", getFileStreamPath("SensorValues.txt").toString());
    }

    catch(FileNotFoundException e)
    {
        e.printStackTrace();
    }

This is what I'm doing. The part until SDCARDPLSWORK is correct, but when it comes to the FILEANDROID log it goes to the private data storage.

使用Environment.getExternalStorageDirectory()作为SD卡路径。

Environment.getExternalStorageDirectory()+"/yourFilename.png"

getFileStreamPath(..) reads from local directory. Your debug code is wrong.

Environment.getExternalStorageDirectory() will get the root folder of sdcard.

@JAVADOC

Applications should not directly use this top-level directory, in order to avoid polluting the user's root namespace. Any files that are private to the application should be placed in a directory returned by Context.getExternalFilesDir, which the system will take care of deleting if the application is uninstalled. Other shared files should be placed in one of the directories returned by getExternalStoragePublicDirectory(String).

/data/data/... this location is used to store files for your package, so try the codes below:

File path = getApplicationContext().getFilesDir(); // get your private folder
Log.d("SDCARDPLSWORK", path.toString());
File myFile;
FileOutputStream fos;
try {
    myFile = new File(path.getAbsolutePath(),
            "SensorValues.txt");
    boolean i = myFile.createNewFile();
    Log.d("SDCARDPLSWORK", myFile.toString() + " " + i);
    fos = new FileOutputStream(myFile);
    Log.d("FILEANDROID", getFileStreamPath("SensorValues.txt")
            .toString());
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM