Android filewriter为null

时间:2013-02-02 20:06:08

标签: android nullpointerexception filewriter

我的应用可以收集一些数据,我只想将这些数据输出到SD卡中的txt文件。

出于某种原因,以下代码适用于Galaxy,但不适用于Nexus。我猜这个代码有些问题。

//name of the file
        String name = "rawData " + year +
                "-" + month + "-" + date + "- " + hour + ":" + minute+ ".txt";

        // create a folder stores all the txt file.
        File root = new File(Environment.getExternalStorageDirectory(), "rawData");
        if (!root.exists()) {
            root.mkdirs();
        }

        // creates a file and a file writer
        File gpxfile = new File(root, name);
        FileWriter writer = null;
        try {
            writer = new FileWriter(gpxfile);
            Log.d(TAG, "The writer is created");
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        Log.d(TAG, "Is the writer null? " + writer);

Here is the logcat

非常感谢!

2 个答案:

答案 0 :(得分:1)

更改此

File root = new File(Environment.getExternalStorageDirectory(), "rawData");

File root = Environment.getExternalStorageDirectory();

答案 1 :(得分:1)

外部存储通常是fat32文件系统,文件名中不允许使用:个字符 顺便说一句,在使用mkdirs()之前,您不需要检查是否存在。