android创建txt文件,读取txt文件内容
16lz
2021-01-24
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);//把字节输出流转Stringreturn 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;}
更多相关文章
- Android第十二课 jni函数的静态绑定
- Android(安卓)采用pull解析xml文件
- 出现add 'tools:replace="android:value"' to element at Androi
- [Android] ICS | JB 锁屏农历的添加
- Android(安卓)Gradle
- Android(安卓)studio 打包aar
- Android无EditText时获取扫描设备的扫描结果
- 签名keystore一系列
- tiny210 android 移植过程中的几个问题