android读写文件操作

本文详细介绍了Android应用中如何进行文件的保存、追加、读取等操作,并提供了将文件保存到SD卡的方法。同时,文章还讲解了不同文件操作模式的区别,如私有模式、可读模式和可写模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


package com.example.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.os.Environment;


public class FileService {
private Context context;
public FileService(Context context){
this.context=context;
}
/**
* 保存文件
* @param name
* @param content
* @throws FileNotFoundException
*/
public void save(String name,String content) throws Exception{
//私有操作模式:创建出来的文件仅能被本应用访问,其它应用无法访问该文件。
//另会覆盖原文件的内容
FileOutputStream o=context.openFileOutput(name, Context.MODE_PRIVATE);
write(content, o);
}

/**
* 写入
* @param content
* @param o
* @throws IOException
*/
private void write(String content, FileOutputStream o) throws IOException {
o.write(content.getBytes());
o.close();
}

/**
* 追加文件
* @param filename
* @param content
* @throws Exception
*/
public void saveAppend(String filename,String content)throws Exception{
FileOutputStream o=context.openFileOutput(filename, Context.MODE_APPEND);//保存在手机自带的文件里面
write(content, o);
}

/**
* 文件,当前文件可以被其他应用读取
* @param filename
* @param content
* @throws Exception
*/
public void saveReadable(String filename,String content)throws Exception{
FileOutputStream o=context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
write(content, o);
}

/**
* 保存文件到SD卡上.需要申请往SD卡写入数据的权限
* @param filename
* @param content
* @throws Exception
*/
public void saveToSDCard(String filename,String content)throws Exception{
File file=new File(Environment.getExternalStorageDirectory(),filename);
FileOutputStream o=new FileOutputStream(file);
o.write(content.getBytes());
o.close();
}

/**
* 当前文件可以被其他应用写入
* @param filename
* @param content
* @throws Exception
*/
public void saveWriteable(String filename,String content)throws Exception{
FileOutputStream o=context.openFileOutput(filename, Context.MODE_WORLD_WRITEABLE);
write(content, o);
}
/**
* 读取文件
* @param filename
* @return
* @throws Exception
*/
public String read(String filename)throws Exception{
FileInputStream i=context.openFileInput(filename);
ByteArrayOutputStream bs=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len=0;
//-1表示读到文件的末尾
while((len=i.read(buffer))!=-1){
bs.write(buffer,0,len);
}
byte[] data=bs.toByteArray();
return new String(data);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值