android创建txt文件,读取txt文件内容

1.android在sd卡上创建一个txt文件,并且写入内容:

public static boolean saveTxt(String phoneNumber,Context context,String path){
                 //sd卡检测
		 String sdStatus = Environment.getExternalStorageState();
		 if(!sdStatus.equals(Environment.MEDIA_MOUNTED)){
			 Toast.makeText(context, "SD 卡不可用", Toast.LENGTH_SHORT).show();
			 return false;
		 }
               //检测文件夹是否存在
		 File file = new File(path);
		 file.exists();
		 file.mkdirs();
		 String p = path+File.separator+"1.txt";
		 FileOutputStream outputStream = null;
		 try {
                         //创建文件,并写入内容
			 outputStream = new FileOutputStream(new File(p));
			 String msg = new String(phoneNumber);
			 outputStream.write(msg.getBytes("UTF-8"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(outputStream!=null){
				try {
					outputStream.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return true;
	} 
	

 2.读取txt内容

public static String readPhoneNumber(String path){
		byte Buffer[] = new byte[1024];
		//得到文件输入流
		File file = new File(path+File.separator+"1.txt");
		FileInputStream in = null;
		ByteArrayOutputStream outputStream = null;
		try {
			 in = new FileInputStream(file);
			//读出来的数据首先放入缓冲区,满了之后再写到字符输出流中
			int len = in.read(Buffer);
			//创建一个字节数组输出流
			outputStream = new ByteArrayOutputStream();
			outputStream.write(Buffer,0,len);
			//把字节输出流转String
			return new String(outputStream.toByteArray());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(in!=null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(outputStream!=null){
				try {
					outputStream.flush();
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值