android文件的读取方法,Android读取写入文件的方法

参考地址:https://blog.csdn.net/harry_helei/article/details/64910713

1.按行读取指定文件

/**

* 按行读取指定文件,输出到ArrayList

*/

public static void readDataFromFile(String fileName) {

if (fileName == null) return;

File file = new File("/storage/emulated/0/" + fileName);//从内存根目录读取文件

if (file.isDirectory()) {

System.out.println(fileName + " is directory");

return;

} else {

try {

InputStream inputStream = new FileInputStream(file);

if (is != null) {

InputStreamReader inputStreamReader = new InputStreamReader(inputStream );

BufferedReader bfReader= new BufferedReader(inputStreamReader );

String strLine;

List strList = new ArrayList();

while ((strLine= bfReader.readLine()) != null) {

System.out.println(strLine);

strList.add(strLine);//添加到strList中,方便数据处理

}

}

} catch (FileNotFoundException e) {

System.out.println(fileName + " doesn't found!");

} catch (IOException e) {

System.out.println(fileName + " read exception, " + e.getMessage());

}

}

}

2.向指定文件写入数据

/**

* 字符串保存到手机内存设备中

*

* @param str

*/

public static void saveFile(String str, String fileName) {

// 创建String对象保存文件名路径

try {

// 创建指定路径的文件

File file = new File(Environment.getExternalStorageDirectory(), fileName);

// 如果文件不存在

if (file.exists()) {

// 创建新的空文件

if (file.delete()) {

System.out.println("success");

}

}

if (file.createNewFile()) {

// 获取文件的输出流对象

FileOutputStream outStream = new FileOutputStream(file);

// 获取字符串对象的byte数组并写入文件流

outStream.write(str.getBytes());

// 最后关闭文件输出流

outStream.close();

}

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* write data to txt

*/

public static void writeStringToTxt(byte[] array, String fileName) throws IOException {

// 第1步、使用File类找到一个文件

File f = new File("/storage/emulated/0/" + File.separator + fileName); // 声明File对象

// 第2步、通过子类实例化父类对象

Writer out; // 准备好一个输出的对象

out = new FileWriter(f, true); // 通过对象多态性,进行实例化

// 第3步、进行写操作

String str = new String(array) + "\n";

out.write(str);// 将内容输出,保存文件

// 第4步、关闭输出流

out.close();// 关闭输出流

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值