Android:使用createNewFile()方法创建文件

时间:2011-08-10 13:58:01

标签: android

如android文档中所述,要创建一个位于应用程序目录中的新文件,Context类中的方法为openFileOutput()

但如果我使用createNewFile()类中的简单File方法,那么文件位于何处。?

5 个答案:

答案 0 :(得分:30)

CreateNewFile()使用如下:

File file = new File("data/data/your package name/test.txt");
if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

因此,您将告诉文件应在何处创建。请记住,您只能在包装上创建新文件。那就是“数据/数据/您的包名/”。

答案 1 :(得分:4)

不知怎的createNewFile()无法在我的设备上创建完整的文件路径。

try {
    if (!futurePhotoFile.exists()) {
        new File(futurePhotoFile.getParent()).mkdirs();
        futurePhotoFile.createNewFile();
    }
} catch (IOException e) {
    Log.e("", "Could not create file.", e);
    Crouton.showText(TaskDetailsActivity.this,
            R.string.msgErrorNoSdCardAvailable, Style.ALERT);
    return;
}

答案 2 :(得分:0)

它将存储在classPath指向的当前目录

答案 3 :(得分:0)

取决于传递给File构造函数的路径。如果父目录存在,并且您当然有权写入它。

答案 4 :(得分:0)

createNewFile()方法的文档说:

当且仅当具有该抽象路径名的文件尚不存在时,以原子方式创建一个新的空文件。检查文件是否存在以及是否创建文件(如果文件不存在)是单个操作,对于可能影响文件的所有其他文件系统活动而言,这是原子操作。

因此,我们不需要手动检查文件是否存在:

val dir = context.filesDir.absolutePath + "/someFolder/"
val logFile = File(dir + "log.txt")
try {
    File(dir).mkdirs()     // make sure to call mkdirs() when creating new directory
    logFile.createNewFile()
} catch (e: Exception) {
    e.printStackTrace()
}
相关问题