Android 读写文件转为String[]

来源:互联网 发布:log4j 日志写入数据库 编辑:程序博客网 时间:2024/06/11 07:50

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;    }




原创粉丝点击