1. 读取操作
String path = "/sdcard/foo.txt";
String content = ""; //文件内容字符串
//打开文件
File file = new File(path);
//如果path是传递过来的参数,可以做一个非目录的判断
if (file.isDirectory()){
Toast.makeText(EasyNote.this, "没有指定文本文件!", 1000).show();
}
else{
try {
InputStream instream = new FileInputStream(file);
if (instream != null) {
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
//分行读取
while (( line = buffreader.readLine()) != null) {
content += line + "\n";
}
instream.close();
} catch (java.io.FileNotFoundException e) {
Toast.makeText(EasyNote.this, "文件不存在", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
2. 写入操作
String filePath = "/sdcard/foo2.txt";
String content = "这是将要写入到文本文件的内容";
//如果filePath是传递过来的参数,可以做一个后缀名称判断; 没有指定的文件名没有后缀,则自动保存为.txt格式
if(!filePath.endsWith(".txt") && !filePath.endsWith(".log"))
filePath += ".txt";
//保存文件
File file = new File(filePath);
try {
OutputStream outstream = new FileOutputStream(file);
OutputStreamWriter out = new OutputStreamWriter(outstream);
out.write(content);
out.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}