简体   繁体   中英

creating and writing to a file in SD card

Annoyingly I had the code below creating and writing to a file on the sdcard, then continued to develop some more code. However I must have changed something, since now it doesnt work.

Its been a long and annoying day, so i was wondering if someone could point out the simple mistake I have done.

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy / hh-mm-ss");
Date curDate = new Date();
String stringDate = sdf.format(curDate);
String resultLogFile = "logFile " + stringDate;

File newFile = new File("sdcard/" + (resultLogFile));
if (!newFile.exists()) {
    try {
        newFile.createNewFile();
    }
    catch (IOException e) {
        e.printStackTrace();
    }

}
try {
    BufferedWriter buf = new BufferedWriter(new FileWriter(newFile, true));
    buf.append(writeToFileString);
    buf.newLine();
    buf.close();
} catch (IOException e) {
    e.printStackTrace();
}

and here is the console:

09-19 17:58:16.270: W/System.err(10411): java.io.IOException: open failed: ENOENT (No such file or directory)
09-19 17:58:16.275: W/System.err(10411):    at java.io.File.createNewFile(File.java:940)
09-19 17:58:16.275: W/System.err(10411):    at android.Maps.GeneticAlgorithm3.shufflePerm3(GeneticAlgorithm3.java:192)
09-19 17:58:16.275: W/System.err(10411):    at android.Maps.HomeScreen$6.onClick(HomeScreen.java:334)
09-19 17:58:16.275: W/System.err(10411):    at android.view.View.performClick(View.java:4084)
09-19 17:58:16.275: W/System.err(10411):    at android.view.View$PerformClick.run(View.java:16966)
09-19 17:58:16.275: W/System.err(10411):    at android.os.Handler.handleCallback(Handler.java:615)
09-19 17:58:16.275: W/System.err(10411):    at android.os.Handler.dispatchMessage(Handler.java:92)
09-19 17:58:16.275: W/System.err(10411):    at android.os.Looper.loop(Looper.java:137)
09-19 17:58:16.275: W/System.err(10411):    at android.app.ActivityThread.main(ActivityThread.java:4896)

您应该使用Environment.getExternalStorageDirectory()来获取根SD卡位置。

Try using:

File newFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + (resultLogFile));

For the timestamp, you can use the following to get it, and then add it to the end of the name:

public String date() {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd_hh:mm:ss");  
        df.setTimeZone(TimeZone.getTimeZone("PST"));  
        return df.format(new Date());
}

Also, make sure you haven't mounted the SD Card via USB on your computer etc, as that would make it unavailable to apps for the time it is mounted.

我想你应该有"/sdcard/"而不是"sdcard/"

The SD card location it is manufacturer dependent. When you are using phone with IDE, you can choose USB mass storage, and None, for USB connection. If you choose USB mass storage than the SD card it is not available to your app :)

I have used the sample code to check it:

boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // We can read and write the media
            mExternalStorageAvailable = mExternalStorageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // We can only read the media
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
        } else {
            // Something else is wrong. It may be one of many other states, but
            // all we need
            // to know is we can neither read nor write
            mExternalStorageAvailable = mExternalStorageWriteable = false;
        }

        if (mExternalStorageAvailable && mExternalStorageWriteable) {
            doWriteForExternalStorage();
        } else {
            Log.d(TAG, "mExternalStorageAvailable: " + mExternalStorageAvailable + ", mExternalStorageWriteable: " + mExternalStorageWriteable + " it is Connected to PC now?");
        }

and

@SuppressWarnings("unused")
    private void doWriteForExternalStorage() {
        // TODO Auto-generated method stub
        File extDir = Environment.getExternalStorageDirectory();
        Log.d(TAG, "extDir:" + extDir.getAbsolutePath());
        if (extDir.isDirectory() && extDir.canWrite()) {
            File fileData = new File(extDir, "mydata.txt");
            Log.d(TAG, "want to create file: " + fileData.toString());
            FileOutputStream fos = null;
            try {
                boolean append = true;
                fos = new FileOutputStream(fileData, append);
                BufferedOutputStream bos = new BufferedOutputStream(fos, 8192);// 8kbyte
                                                                                // buff,
                                                                                // it
                                                                                // should
                                                                                // be
                                                                                // plenty

                StringBuilder sb = new StringBuilder("\n");
                List<RunningTaskInfo> runningTasks = activityManager.getRunningTasks(100);

                if (runningTasks != null) {
                    for (RunningTaskInfo runningTask : runningTasks) {
                        sb.append("runningTask: ").append(runningTask.baseActivity.getPackageName()).append(", ").append(runningTask.baseActivity.getClassName());
                    }
                } else {
                    sb.append("No running tasks");
                }
                byte[] data = sb.toString().getBytes();
                bos.write(data);
                bos.flush();


                             bos.close();
            fos = null;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null ) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

to log the services

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