Android文件创建

时间:2015-08-05 02:22:02

标签: android file

我正在尝试在Android的公共目录中创建一个文件。

它适用于大多数设备,但我遇到Android Mini PC的问题。我可以在其中创建一个文件夹,但无法创建文件。

String iconsStoragePath =  Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES).getAbsolutePath()+"/ab";
File dir = new File(iconsStoragePath);
dir.mkdirs();
File file = new File(iconsStoragePath, info.path.toString().replace("/", ""));

1 个答案:

答案 0 :(得分:1)

首先,不要忘记在AndroidManifest.xml上声明正确的权限。

<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    ...
</manifest>

然后,检查外部存储器是否已安装。

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

请勿忘记检查存储空间是否有足够的空间来使用File.getFreeSpace()保存文件。

现在,请尝试以下操作:

File dir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_MOVIES);
if (!dir.mkdirs()) {
    Log.w("LOG","Directory not created!");
    // Handle this error here, or return.
}

File file = new File(dir, "YourFile.txt");

// Do whatever you want now like the example below...
try {
    FileOutputStream fos = new FileOutputStream(file);
    PrintWriter pw = new PrintWriter(fos);
    pw.println("Hello world!");
    pw.flush();
    pw.close();
    fos.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
    Log.i("Your_TAG", "File not found! Don't forget WRITE_EXTERNAL_STORAGE on your manifest!");
} catch (IOException e) {
    e.printStackTrace();
    Log.e("Your_TAG","Some IO error occurred...");
}  

有关详细信息,您可以查看有关如何保存文件的this tutorialEnvironment课程中的the docs