美文网首页
文件读写(外部存储方式)

文件读写(外部存储方式)

作者: 陈陈_04d0 | 来源:发表于2020-09-11 11:25 被阅读0次

StringBuilder content =new StringBuilder();

try {

File eFile =new File(getFilePath(this,"Test")+File.separator+"SSS.text");

    if (!eFile.exists())

   eFile.createNewFile();

    FileOutputStream outputStream =new FileOutputStream(eFile);

    String str ="hello word" +"\n" +"android" 

    outputStream.write(str.getBytes());

    outputStream.close();

    InputStreamReader bufferedInputStream =new InputStreamReader(new FileInputStream(eFile));

    BufferedReader buffreader =new BufferedReader(bufferedInputStream);

    String line;

    while ((line = buffreader.readLine()) !=null) {//一行一行读取

 content.append(line).append("\n");

    }

Log.e("afterInCreate", content.toString());

    bufferedInputStream.close();

}catch (FileNotFoundException e) {

e.printStackTrace();

}catch (IOException e) {

e.printStackTrace();

}

public static StringgetFilePath(Context context, String dir) {

String directoryPath="";

    if (MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ) {//判断外部存储是否可用

        directoryPath =context.getExternalFilesDir(dir).getAbsolutePath();

    }else{//没外部存储就使用内部存储

        directoryPath=context.getFilesDir()+File.separator+dir;

    }

File file =new File(directoryPath);

    if(!file.exists()){//判断文件目录是否存在

        file.mkdirs();

    }

return directoryPath;

}

相关文章

网友评论

      本文标题:文件读写(外部存储方式)

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