Android 读写文件转为String[]

1.写入文件中

String filePath = Environment.getDataDirectory()+"/test";
    private void writeData(){
            String str = "com.android.mms";
            try {
                File file = new File(filePath);
                if (!file.exists()) {
                    File dir = new File(file.getParent());
                    dir.mkdirs();
                    file.createNewFile();
                }
                FileOutputStream outStream = new FileOutputStream(file,true);
                outStream.write(str.getBytes());
                if(fileHasContent()){
                    outStream.write("/".getBytes());
                }
                outStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

 FileOutputStream outStream = new FileOutputStream(file,true);
第二个参数代表是否要在文件的后面追加,true为在文件的末尾追加,false则会将原来的内容给替换掉

outStream.write("/".getBytes());
每写入一个内容用一个“/”分隔开。


2.读文件并将文件内容转为String和String[]两种。

    private String[] readData(){
        String str = "";
        String[] aa = null;
        try{
            FileInputStream fin = new FileInputStream(filePath);
            int length = fin.available();
            byte[] buffer = new byte[length];
            fin.read(buffer);
            str = new String(buffer);
            Log.i(TAG,"lsn str = "+str);

            aa = str.split("/");
            for (int i=0;i<aa.length;i++){
                Log.i(TAG,"lsn aa["+i+"] = "+aa[i]);
            }
            fin.close();
        }catch (Exception e){

        }
        return aa;
    }

3.判断是否需要添加分隔符。

    private boolean fileHasContent(){
        try{
            FileInputStream fin = new FileInputStream(filePath);
            int length = fin.available();
            Log.i(TAG,"lsn length = "+length);
            if(length>0){
                return true;
            }
        }catch (Exception e){

        }
        return false;
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值