简体   繁体   English

创建和写入SD卡中的文件

[英]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. 令人讨厌的是,我在下面的代码创建并写入sdcard上的文件,然后继续开发更多代码。 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. 此外,请确保您没有通过USB在计算机上安装SD卡等,因为这会使应用程序在安装时无法使用。

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

The SD card location it is manufacturer dependent. SD卡的位置取决于制造商。 When you are using phone with IDE, you can choose USB mass storage, and None, for USB connection. 当您使用带IDE的电话时,您可以选择USB大容量存储,而选择无,用于USB连接。 If you choose USB mass storage than the SD card it is not available to your app :) 如果您选择USB大容量存储而不是SD卡,则您的应用无法使用它:)

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 记录服务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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