Android 文件操作操作时,要赋予相应的权限:
<uses-permission android:name=
"android.permission.WRITE_EXTERNAL_STORAGE"
/>
|
下面是向文件写文本的代码:
private
final
static
String PATH =
"/sdcard/lin"
;
private
final
static
String FILENAME =
"/test.txt"
;
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
writeFile();
}
private
void
writeFile() {
//判断设备是否存在sdcard
if
(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
try
{
Log.d(
"File Operation"
,
"start!"
);
File path =
new
File(PATH);
File file =
new
File(PATH+FILENAME);
//如果不存在此路径,则创建此路径
if
(!path.exists()) {
path.mkdir();
}
//如果不存在此文件,则创建此文件
if
(!file.exists()) {
file.createNewFile();
}
//将"text message!"信息写入相应的文件
OutputStreamWriter osw =
new
OutputStreamWriter(
new
FileOutputStream(file));
osw.write(
"text message!"
);
osw.close();
Log.d(
"File Operation"
,
"success!"
);
}
catch
(Exception e) {
Log.d(
"File Operation"
,
"file create error"
);
}
}
}
|
本文转自Work Hard Work Smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/archive/2013/03/28/2981190.html,如需转载请自行联系原作者