手机中的文件保存在对应的目录 /data/data/包名/文件名
具体的实现实例
package com.example.shoujicunwenjian822.server;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class LoginService {
/**
* 保存用户登陆信息的业务方法
* @param user
* @param pass
* @return
*/
public static String saveLoginInfo(String user,String pass)
{
String res="";
res="before file";
File file = new File("/data/data/com.example.shoujicunwenjian822/user.txt");
res="before try";
try {
FileOutputStream fos = new FileOutputStream(file);
res="before wirite";
fos.write((user+"##"+pass).getBytes());
res="before close";
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
}运行之后就可以在结果如图所示
成功保存信息到手机中了
不够这样直接写包名,不利于程序的该进,优化后的写法如下
package com.example.shoujicunwenjian822.server;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
public class LoginService {
/**
* 保存用户登陆信息的业务方法
* @param user
* @param pass
* @return
*/
public static String saveLoginInfo(Context context,String user,String pass)
{
//boolean res=false;
String res=context.getFilesDir().toString();//返回文件路径
//File file = new File("/data/data/com.example.shoujicunwenjian822/user.txt");
File file = new File(res,"info.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write((user+"##"+pass).getBytes());
//res=true;
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
}
放到缓存目录是把
context.getFilesDir()改为context.getCacheDir()就可以了,不用不能超过1M