Android 文件读写和写入日志

1.读取raw下的text文件

InputStream inputStream = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;
        try {
            //得到资源中的Raw数据流
            inputStream = getResources().openRawResource(R.raw.test);
            reader = new InputStreamReader(inputStream);// 字符流
            bufferedReader = new BufferedReader(reader); //缓冲流
            StringBuilder result = new StringBuilder();
            String temp;
            while ((temp = bufferedReader.readLine()) != null) {
                result.append(temp);
            }
            Log.i("MainActivity", "result:" + result);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

2.读取assets下的text文件

 InputStream inputStream = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;
        try {
            //得到资源中的asset数据流
            inputStream = getResources().getAssets().open("test.txt");
            reader = new InputStreamReader(inputStream);// 字符流
            bufferedReader = new BufferedReader(reader); //缓冲流
            StringBuilder result = new StringBuilder();
            String temp;
            while ((temp = bufferedReader.readLine()) != null) {
                result.append(temp);
            }
            Log.i("MainActivity", "result:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

读写 data/data/包名 

     //写
        String text = "hello world 666";
        File file1=new File("/data/data/com.example.myapplication/","test.txt");
        FileOutputStream fileOutputStream = null;//com.example.myapplication
        try {
            fileOutputStream = new FileOutputStream(file1);
            fileOutputStream.write(text.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }



//读

 InputStream inputStream = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;
        try {
            File file=new File("/data/data/com.example.myapplication/", "test.txt");
            inputStream = new FileInputStream(file);
            reader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(reader);
            StringBuilder result = new StringBuilder();
            String temp;
            while ((temp = bufferedReader.readLine()) != null) {
                result.append(temp);
            }
            Log.i("MainActivity", "result:" + result);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

/mnt/sdcard目录文件读写

/storage/emulated/0/Android/data/com.example.myapplication/files

private void readSdcard() {
        InputStream inputStream = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;

        File[] externalStorageVolumes =
                ContextCompat.getExternalFilesDirs(getApplicationContext(), null);
        File primaryExternalStorage = externalStorageVolumes[0];
//                File file2 = new File(this.getFilesDir().getPath() + "test5.txt"); //  写到 /data 目录下面
        Log.d("测试 primaryExternalStorage", "writeSdcard: " + primaryExternalStorage.getPath());
        File file = new File(primaryExternalStorage, "test5.txt");
        try {
            inputStream = new FileInputStream(file);
            reader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(reader);
            StringBuilder result = new StringBuilder();
            String temp = null;
            while (true) {
                try {
                    if (!((temp = bufferedReader.readLine()) != null)) break;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                result.append(temp);
            }
            Log.i("MainActivity 读取到", "result:" + result);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


//        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//                InputStream inputStream = null;
//                Reader reader = null;
//                BufferedReader bufferedReader = null;
//                try {
//                    File storage = Environment.getExternalStorageDirectory();
//                    File tmepfile = new File(storage.getPath());
//                    File file=new File(tmepfile, "test.txt");
//                    inputStream = new FileInputStream(file);
//                    reader = new InputStreamReader(inputStream);
//                    bufferedReader = new BufferedReader(reader);
//                    StringBuilder result = new StringBuilder();
//                    String temp;
//                    while ((temp = bufferedReader.readLine()) != null) {
//                        result.append(temp);
//                    }
//                    Log.i("MainActivity", "result:" + result);
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                } finally {
//                    if (reader != null) {
//                        try {
//                            reader.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    if (inputStream != null) {
//                        try {
//                            inputStream.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    if (bufferedReader != null) {
//                        try {
//                            bufferedReader.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }
//        }
    }





 private void writeSdcard() {
        String text = "hello world 我是写入的数据";

        File[] externalStorageVolumes =
                ContextCompat.getExternalFilesDirs(getApplicationContext(), null);
        File primaryExternalStorage = externalStorageVolumes[0];
//                File file2 = new File(this.getFilesDir().getPath() + "test5.txt"); //  写到 /data 目录下面
        Log.d("测试 primaryExternalStorage", "writeSdcard: " + primaryExternalStorage.getPath());
        File file1 = new File(primaryExternalStorage, "test5.txt");
        if (!file1.exists()) {
            try {
                file1.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file1);
            fileOutputStream.write(text.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

//        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//                File storage = Environment.getExternalStorageDirectory();
//                File tmepfile = new File(storage.getPath());
//                if (! tmepfile.exists()) {
//                    tmepfile.mkdirs();
//                }
//                File file1=new File(tmepfile,"test.txt");
//
//                if (!file1.exists()){
//                    try {
//                        file1.createNewFile();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//                FileOutputStream fileOutputStream = null;
//                try {
//                    fileOutputStream = new FileOutputStream(file1);
//                    fileOutputStream.write(text.getBytes());
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }finally {
//                    if (fileOutputStream != null) {
//                        try {
//                            fileOutputStream.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }
//        }
    }

写的是安卓11的 注解是博主写的

 <!--文件读写权限-->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application 
   android:name="builder.Myapp">
        
    </application>


//Application 
public class Myapp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        MyLog crashHandler = MyLog.getInstance();
        crashHandler.init(this);
    }
}


public class MyLog {
    public  Context context;
    private MyLog() { }
    private static MyLog instance = new MyLog();
    public static MyLog getInstance() {
        return instance;
    }
    public MyLog init(Context context) {
        this.context = context;
        MYLOG_PATH_SDCARD_DIR="/data/data/"+context.getPackageName()+"/";
        return this;
    }
    //记得改包名
    private  String MYLOG_PATH_SDCARD_DIR ;// 日志文件的路径
    private static String MYLOG_FILE_NAME = "-Log.txt";// 日志文件名称
    private static Boolean MYLOG_SWITCH = true; // 日志文件总开关
    private static Boolean MYLOG_WRITE_TO_FILE = true;// 日志写入文件开关
    private static char MYLOG_TYPE = 'v';// 输入日志类型,w代表只输出告警信息等,v代表输出所有信息
    private static int SDCARD_LOG_FILE_SAVE_DAYS = 5;// sd卡中日志文件的最多保存天数
    private static String MYLOGFILEName = "Log.txt";// 本类输出的日志文件名称
    private static SimpleDateFormat myLogSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 日志的输出格式
    private static SimpleDateFormat logfile = new SimpleDateFormat("yyyy-MM-dd");// 日志文件格式

    public  void w(String tag, Object msg) { // 警告信息
        log(tag, msg.toString(), 'w');
    }
    public  void e(String tag, Object msg) { // 错误信息
        log(tag, msg.toString(), 'e');
    }
    public  void d(String tag, Object msg) {// 调试信息
        log(tag, msg.toString(), 'd');
    }
    public  void i(String tag, Object msg) {//
        log(tag, msg.toString(), 'i');
    }
    public  void v(String tag, Object msg) {
        log(tag, msg.toString(), 'v');
    }
    public  void w(String tag, String text) {
        log(tag, text, 'w');
    }
    public  void e(String tag, String text) {
        log(tag, text, 'e');
    }
    public  void d(String tag, String text) {
        log(tag, text, 'd');
    }
    public  void i(String tag, String text) {
        log(tag, text, 'i');
    }
    public  void v(String tag, String text) {
        log(tag, text, 'v');
    }

    /**
     * 根据tag, msg和等级,输出日志
     * @param tag
     * @param msg
     * @param level
     */
    private  void log(String tag, String msg, char level) {
        if (MYLOG_SWITCH) {//日志文件总开关
            if ('e' == level && ('e' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) { // 输出错误信息
                Log.e(tag, msg);
            } else if ('w' == level && ('w' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {
                Log.w(tag, msg);
            } else if ('d' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {
                Log.d(tag, msg);
            } else if ('i' == level && ('d' == MYLOG_TYPE || 'v' == MYLOG_TYPE)) {
                Log.i(tag, msg);
            } else {
                Log.v(tag, msg);
            }
            if (MYLOG_WRITE_TO_FILE)//日志写入文件开关
                writeLogtoFile(String.valueOf(level), tag, msg);
        }
    }

    /**
     * 打开日志文件并写入日志
     * @param mylogtype
     * @param tag
     * @param text
     */
    @SuppressLint("LongLogTag")
    private  void writeLogtoFile(String mylogtype, String tag, String text) {// 新建或打开日志文件
        Date nowtime = new Date();
        String needWriteFiel = logfile.format(nowtime);
        String needWriteMessage = myLogSdf.format(nowtime) + "    " + mylogtype + "    " + tag + "    " + text;

        // data/data/包名下面 不能直接打开看,可以用设备文件浏览器打开看 开发测试用
//        File file=new File(MYLOG_PATH_SDCARD_DIR,needWriteFiel+MYLOG_FILE_NAME);

        //内部存储设备/Android/data/包名/files 文件保存在手机上 可以打开来看
        File[] externalStorageVolumes = ContextCompat.getExternalFilesDirs(context.getApplicationContext(), null);
        File primaryExternalStorage = externalStorageVolumes[0];
        Log.d("测试 primaryExternalStorage", "writeSdcard: " + primaryExternalStorage.getPath());
        File file = new File(primaryExternalStorage, needWriteFiel+MYLOG_FILE_NAME);


        if (!file.exists()) {
            try {
                //在指定的文件夹中创建文件
                file.createNewFile();
            } catch (Exception e) {
            }
        }
        try {
            FileWriter filerWriter = new FileWriter(file, true);// 后面这个参数代表是不是要接上文件中原来的数据,不进行覆盖
            BufferedWriter bufWriter = new BufferedWriter(filerWriter);
            bufWriter.write(needWriteMessage);
            bufWriter.newLine();
            bufWriter.close();
            filerWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    /**
//     * 删除制定的日志文件
//     */
//    public  void delFile() {// 删除日志文件
//        String needDelFiel = logfile.format(getDateBefore());
//        File dirPath = Environment.getExternalStorageDirectory();
//        File file = new File(dirPath, needDelFiel + MYLOGFILEName);// MYLOG_PATH_SDCARD_DIR
//        if (file.exists()) {
//            file.delete();
//        }
//    }
//    /**
//     * 得到现在时间前的几天日期,用来得到需要删除的日志文件名
//     */
//    private  Date getDateBefore() {
//        Date nowtime = new Date();
//        Calendar now = Calendar.getInstance();
//        now.setTime(nowtime);
//        now.set(Calendar.DATE, now.get(Calendar.DATE) - SDCARD_LOG_FILE_SAVE_DAYS);
//        return now.getTime();
//    }
}







//下面是activity 调用

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};
    private void initView() {
        checkPermission();
    }
    private void checkPermission() {
        //检查权限(NEED_PERMISSION)是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
                    .WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "请开通相关权限,否则无法正常使用本应用!", Toast.LENGTH_SHORT).show();
            }
            //申请权限
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);

        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_EXTERNAL_STORAGE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    MyLog.getInstance().e("*****","我是测试数据log ggg");
                } else {
                    Toast.makeText(this, "授权被拒绝!", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }

日志是基于安卓11的

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值