Java 在android中创建文件的问题
我正在尝试使用以下代码在目录中创建文件:Java 在android中创建文件的问题,java,android,android-layout,android-intent,android-emulator,Java,Android,Android Layout,Android Intent,Android Emulator,我正在尝试使用以下代码在目录中创建文件: ContextWrapper cw = new ContextWrapper(getApplicationContext()); File directory = cw.getDir("themes", Context.MODE_WORLD_WRITEABLE); Log.d("Create File", "Directory path"+directory.getAbsolutePath()); File new_file =n
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("themes", Context.MODE_WORLD_WRITEABLE);
Log.d("Create File", "Directory path"+directory.getAbsolutePath());
File new_file =new File(directory.getAbsolutePath() + File.separator + "new_file.png");
Log.d("Create File", "File exists?"+new_file.exists());
当我从EclipseDDMS检查emulator的文件系统时,我可以看到创建了一个目录“app_themes”。但是在里面我看不到“new_file.png”。日志显示新的_文件不存在。有人能告诉我是什么问题吗
问候,,
Anees试试这个
File new_file =new File(directory.getAbsolutePath() + File.separator + "new_file.png");
try
{
new_file.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Create File", "File exists?"+new_file.exists());
但是要确定
public boolean createNewFile ()
根据存储在此文件中的路径信息在文件系统上创建新的空文件。如果此方法创建文件,则返回true;如果文件已存在,则返回false。请注意,即使文件不是文件,它也会返回false(例如,因为它是一个目录) 创建文件对象并不意味着将创建文件。如果要创建空文件,可以调用
new\u file.createNewFile()
。或者你可以写一些东西给它。创建一个文件
实例并不一定意味着该文件存在。您必须在文件中写入一些内容才能在物理上创建它
File directory = ...
File file = new File(directory, "new_file.png");
Log.d("Create File", "File exists? " + file.exists()); // false
byte[] content = ...
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(content);
out.flush(); // will create the file physically.
} catch (IOException e) {
Log.w("Create File", "Failed to write into " + file.getName());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
或者,如果您想创建一个空文件,您可以调用
file.createNewFile();