`
wangfeiaini
  • 浏览: 53400 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

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;
	}
	

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics