android文件读写

公司最近要做一个测试工具,其中要用到文件的读写,因为以前学Java的时候对文件操作这方面写的比较少,正好有此机会也当是练手了。 要求就是把指定的logcat信息拼成字符串然后保存到本地文件,优先保存到外置SD卡,当没有检测到外置SD卡时,保存到本地存储,代码如下

private File file = nullprivate FileOutputStream outputStream = null;
private InputStreamReader fileReader = null;
// write file to local External SD-Card or Built-in SD-Card
    public void writeFileToLocal(String content){
        try {
            if(checkSDCardIsMounted()){
                FILENAME = CARD + "qtb01testlog.txt";
            }else{
                FILENAME = Environment.getExternalStorageDirectory().toString() + File.separator + "qtb01testlog.txt";
            }
            file = new File(FILENAME);
            if(file.exists()){
                file.delete();
            }else{
                file.createNewFile();   
            }
            outputStream  = new FileOutputStream(file,true);
            outputStream.write(content.getBytes("utf-8"));  
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
// get the file path
public String getFilePath(){
    return file.getPath();

}
// read file
    public synchronized String readLocaFile(String filePath) {
        String fileContent = "";
        try {  
            file = new File(filePath);
            if(file.isFile() && file.exists()){
                fileReader = new InputStreamReader(new FileInputStream(file),"UTF-8");
                BufferedReader reader=new BufferedReader(fileReader);
                String line;
                while ((line = reader.readLine()) != null) {
                    fileContent += line+"\n";
                }   
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileContent;
    }
// set decimal point of three
public static String setDecimals(double d){
    DecimalFormat df = new DecimalFormat("#.000");  
    return df.format(d);
}

实际上文件的读写操作是最基本的知识,以流的形式写和度也是最基本的最简单的,必须掌握。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值