【发布时间】:2012-03-22 18:53:28
【问题描述】:
我想将数据写入输出文件并将其保存在移动设备或计算机硬盘上。我可以让我的代码在下面工作,但必须在一个步骤中创建目录,然后在另一个步骤中创建文件。有没有更有效的方法来编写代码,必须在写入文件之前创建一个不存在的目录?
谢谢
StringBuilder Path = new StringBuilder();
Path.append(Environment.getExternalStorageDirectory().toString());
String filename = "test.txt";
String test_text = "Date, Item, Quantity, Description,";
File file = new File(Path.toString()+"/" +"Test Folder2/");
file.mkdirs();
FileOutputStream file_os = null;
try {
File file2 = new File(Path.toString()+"/" +"Test Folder2", filename);
file_os = new FileOutputStream(file2);
OutputStreamWriter osw = new OutputStreamWriter(file_os);
try {
osw.write(test_text);
} catch (IOException e) {
e.printStackTrace();
}
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
Toast.makeText(QuizSettingsActivity.this, Path.toString(),
Toast.LENGTH_LONG).show();
};
【问题讨论】:
-
只要目录不存在,我想你就得创建目录...
标签: java android io outputstream