美文网首页
android 文件操作

android 文件操作

作者: 风___________ | 来源:发表于2018-08-20 17:34 被阅读18次
    • 没做容错。只是简单学习

    删除 date/date/包名/files文件目录下所有文件

    public static void CleanCache(){
           File file = KapApplication.getContext().getFilesDir();
            File[] childrenFiles = file.listFiles();
            for (File childrenFile : childrenFiles){
                if (!childrenFile.isFile()) continue;
                boolean success = childrenFile.delete();
            }
        }
    

    获取 date/date/包名/files文件目录下指定文件

    private static String LoadCache(Context context,String fileNameString){
            FileInputStream inputStream;
            BufferedReader reader = null;
            StringBuilder builder = new StringBuilder();
            try{
                inputStream = context.openFileInput(fileNameString);
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while((line = reader.readLine()) != null){
                    builder.append(line);
                }
            }catch(IOException e){
                e.printStackTrace();
            }finally{
                if(reader != null){
                    try{
                        reader.close();
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                }
            }
            return builder.toString();
        }
    

    保存 文件至date/date/包名/files文件目录下

    // 存数据
        private static void SaveCache(Context context, String contentString, String fileNameString) {
            FileOutputStream outputStream;
            BufferedWriter writer = null;
            try {
                outputStream = context.openFileOutput(fileNameString, Context.MODE_PRIVATE);
                writer = new BufferedWriter(new OutputStreamWriter(outputStream));
                writer.write(contentString);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (writer != null) {
                        writer.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    

    判断文件存在

        public static boolean FileIsExists(String filePath){
            try {
                File f=new File(filePath);
                if(!f.exists()) return false;
            }
            catch (Exception e) {
                return false;
            }
            return true;
        }
    

    相关文章

      网友评论

          本文标题:android 文件操作

          本文链接:https://www.haomeiwen.com/subject/tfwliftx.html