//保存一个字符串到jky.txt
public void save(String content,String name){
try {
// /data/data/com.ccc.file/目录下
File file = new File("/data/data/com.ccc.file",name);
FileOutputStream fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
从一个文件里读
public String read(String name){
String result = null;
try {
File file = new File("/data/data/com.ccc.file",name);
//字节数组输出流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while((len = fis.read(buffer)) != -1){
bos.write(buffer, 0, len);
}
result = bos.toString();
fis.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
//为了方便的去管理文件 context设计了两个方法可以直接获取到输入输出流
public void savePrivate(String content,String name){
try {
/**
* 自己去创建了一个files文件夹
*/
FileOutputStream output = context.openFileOutput(name, Context.MODE_PRIVATE);
output.write(content.getBytes());
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 读取文件
* @param name
* @return
*/
public String readPrivate(String name){
String result = null;
try {
FileInputStream input = context.openFileInput(name);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024*4];
int len = 0;
while((len = input.read(buffer)) != -1){
bos.write(buffer, 0, len);
}
result = bos.toString();
bos.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
如果要即可读又可写,可这样
public void saveWRW(String content,String name){
try {
/**
* 自己去创建了一个files文件夹
*/
FileOutputStream output = context.openFileOutput(name, Context.MODE_WORLD_WRITEABLE|Context.MODE_WORLD_READABLE);
output.write(content.getBytes());
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//在sdcard里面写数据,与sdcard有关的数据与Environment这个类有关 最后还要加上权限 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
public void saveSDCard(String content,String name) throws Exception{
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ //判断sdcard是否存在
File file = new File(Environment.getExternalStorageDirectory(), name);
FileOutputStream fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();
}
}
}