private String readFromFile(Context context){ if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { String foldername = Environment.getExternalStorageDirectory().getPath()+ "/eryaApp"; File folder = new File(foldername); if (folder == null || !folder.exists()) { folder.mkdir(); } File targetFile=new File("/sdcard/eryaApp/eryaShoppingList.txt"); String readedStr=""; try{ if(!targetFile.exists()){ targetFile.createNewFile(); return "No File error "; }else{ InputStream in = new BufferedInputStream(new FileInputStream(targetFile)); BufferedReader br= new BufferedReader(new InputStreamReader(in, "UTF-8")); String tmp; while((tmp=br.readLine())!=null){ readedStr+=tmp; } br.close(); in.close(); return readedStr; } } catch (Exception e) { Toast.makeText(context,e.toString(),Toast.LENGTH_LONG).show(); return e.toString(); } }else{ Toast.makeText(context,"未发现SD卡!",Toast.LENGTH_LONG).show(); return "SD Card error"; } }
private void SavedToText(Context context,String stringToWrite){ if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { String foldername = Environment.getExternalStorageDirectory().getPath()+ "/eryaApp"; File folder = new File(foldername); if (folder == null || !folder.exists()) { folder.mkdir(); } String fileName="/eryaShoppingList"+".txt"; File targetFile = new File(foldername + fileName); OutputStreamWriter osw; try{ if(!targetFile.exists()){ targetFile.createNewFile(); osw = new OutputStreamWriter(new FileOutputStream(targetFile),"utf-8"); osw.write(stringToWrite); osw.close(); }else{ osw = new OutputStreamWriter(new FileOutputStream(targetFile,true),"utf-8"); osw.write("/n"+stringToWrite); osw.flush(); osw.close(); } } catch (Exception e) { Toast.makeText(context,e.toString(),Toast.LENGTH_LONG).show(); } }else{ Toast.makeText(context,"未发现SD卡!",Toast.LENGTH_LONG).show(); } }
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/10526.html