OutputWriter Java或Android
我想将数据写入输出文件,并将其保存在移动设备或计算机硬盘上。我可以让下面的代码正常工作,但必须在一个步骤中创建目录,然后在另一个步骤中创建文件。是否有一种更有效的方法来编写代码,在编写文件之前必须先创建一个不存在的目录 谢谢OutputWriter Java或Android,java,android,io,outputstream,Java,Android,Io,Outputstream,我想将数据写入输出文件,并将其保存在移动设备或计算机硬盘上。我可以让下面的代码正常工作,但必须在一个步骤中创建目录,然后在另一个步骤中创建文件。是否有一种更有效的方法来编写代码,在编写文件之前必须先创建一个不存在的目录 谢谢 StringBuilder Path = new StringBuilder(); Path.append(Environment.getExternalStorageDirectory().toString()); String filename = "
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();
};
有关在外部存储上保存文件的更多详细信息,请按照下面提到的链接进行操作:。只要目录不存在,我认为您就必须创建目录。。。
String FILENAME = "test";
String string = "Date, Item, Quantity, Description,";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();