欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-31 10:41:37
...

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