Androind中读写文件与JAVA中操作完全一直,只是在读写文件时需要在AndroidMainFest.xml文件中添加android.permission.WRITE_EXTERNAL_STORAGE权限。
写操作主要用到的对象是File,PrintStream,FileOutStream三个对象。
示例代码如下:
String path;
path = Environment.getExternalStorageDirectory()+File.separator+"filetest"+File.separator+"file1.txt";
File file = new File(path);
PrintStream ps=null ;
if (!file.getParentFile().exists())
{
file.getParentFile().mkdir();
}
try {
ps = new PrintStream(new FileOutputStream(file));
ps.println("书名:android入门与提高");
ps.println("作者:张三");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
ps.close();
}
}
读操作主要用到Scanner,FileInputStream,File三个对象。
示例代码如下:
String path;
path = Environment.getExternalStorageDirectory()+File.separator+"filetest"+File.separator+"file1.txt";
File file = new File(path);
FileInputStream fs = null;
if(!file.exists())
{
Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
return;
}
try {
fs = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner scan = new Scanner(fs);
sb = new StringBuffer();
while(scan.hasNext()){
sb.append(scan.next());
}
Toast.makeText(getApplicationContext(), sb.toString(), Toast.LENGTH_SHORT).show();
}
});