android怎样读文本文件的内容
答案:2 悬赏:30
解决时间 2021-02-12 14:24
- 提问者网友:小姐请专情
- 2021-02-12 00:08
android怎样读文本文件的内容
最佳答案
- 二级知识专家网友:无字情书
- 2021-02-12 01:20
bufferedinputstream in = new bufferedinputstream(is);reader = new bufferedreader(new inputstreamreader(in, "utf-8"));读取之后直接转换成 utf-8格式再展示,因为utf-8兼容所有语言的编码方式
全部回答
- 1楼网友:两不相欠
- 2021-02-12 02:46
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();
}
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯
• 手机登qq时,显示手机磁盘不足,清理后重新登 |
• 刺客的套装怎么选啊? |