android保存文件到手机

手机中的文件保存在对应的目录 /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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旺哥是我

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值