首页 > 代码库 > 用IO流向存储器或SD卡中存入/读取字符的工具类

用IO流向存储器或SD卡中存入/读取字符的工具类

FileManager

package com.kale.utils;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintStream;import android.content.Context;import android.os.Environment;/** * @author:Jack Tony * @tips  : *  <!-- 读写SD卡的权限 -->    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> * @date  :2014-6-30 */public class FileManager {    private String SD_PATH;    private String fileName;    private String dirName;    public String getSD_PATH() {        return SD_PATH;    }        /**     * @param permission 是否添加了权限     */    public FileManager(boolean permission) {        //得到当前外部存储设备的目录        SD_PATH = Environment.getExternalStorageDirectory() + "/";    }        /**     * 在SD卡上创建文件     *      * @throws IOException     */    public File creatSDFile(String dirName ,String fileName) throws IOException {        this.fileName = fileName;        this.dirName = dirName;        File file = new File(creatSDDir(dirName), fileName);        return file;    }            public String getFileWholePath() throws IOException{        if (dirName == null || fileName == null) {            return SD_PATH + dirName + "/" + fileName;        }        else {            throw new IOException("can‘t find dirName or fileName");        }            }        /**     * 在SD卡上创建目录     *      * @param dirName     */    public File creatSDDir(String dirName) {        File dir = new File(SD_PATH + dirName);        dir.mkdir();        return dir;    }        /**     * 判断SD卡上的文件夹是否存在     * kale,file.txt->kale/file.txt     */    public boolean isFileExist(String dirName ,String fileName){        File file = new File(SD_PATH +dirName+"/"+ fileName);        return file.exists();    }        /**     * 将一个InputStream里面的数据写入到SD卡中     * example:kale,file.txt,inputStream->kale/file.txt     * InputStream is = new ByteArrayInputStream( "kale data".getBytes() );       manager.saveToSdCard("dir02", "kale.txt", is );     */    public File saveToSDcard(String dirName,String fileName,InputStream input){        File file = null;        OutputStream output = null;        try{            //创建目录            creatSDDir(dirName);            //建立文件            file = creatSDFile(dirName ,fileName);            output = new FileOutputStream(file);            byte buffer [] = new byte[5 * 1024];            //int count = 0;            while((input.read(buffer)) != -1){                //String str = new String(buffer,0,count);                //str = new String(str.getBytes("iso-8859-1"),"utf-8");                                /*System.out.println("---------File Manager----start--------");                System.out.println(str);                System.out.println("---------File Manager-----end-------");*/                output.write(buffer);            }            output.flush();        }        catch(Exception e){            e.printStackTrace();        }        finally{            try{                output.close();            }            catch(Exception e){                e.printStackTrace();            }        }        return file;    }        /**     * @param dirName     * @param fileName     * @return 从sd卡中读取文件的字符,返回String     * @throws Exception     */    public String readFromSDcard(String dirName,String fileName) throws FileNotFoundException {        try {            File file = new File(SD_PATH +dirName+"/"+ fileName);            FileInputStream fis = new FileInputStream(file);            BufferedReader br = new BufferedReader(new InputStreamReader(fis));            StringBuilder sb = new StringBuilder("");            String line = null;            //循环读取文件内容            while((line = br.readLine()) != null) {                sb.append(line);            }            br.close();            return sb.toString().trim();        }         catch(FileNotFoundException e) {            e.printStackTrace();            throw new FileNotFoundException("no such file");        }        catch (Exception e) {            e.printStackTrace();        }        return null;    }        /////////////////////// 直接读取包名文件夹下的文件,而不是SD卡中的 /////////////////////    /**     * @param str     * 将string写入到data/data/包名/files中     * example:write(file.txt ,data)     */    public static void write(Context mContext,String fileName,String str) {        try {            /**             * MODE_PRIVATE:该文件只能被当前程序读写 MODE_APPEND:用追加方式打开文件,新写入的内容追加到末尾             * MODE_WORLD_READABLE:该文件内容可以被其他程序读             * MODE_WORLD_WRITEABLE:该文件内容可以被其他程序读写             */            FileOutputStream fos = mContext.openFileOutput(fileName, Context.MODE_PRIVATE | Context.MODE_APPEND);            PrintStream ps = new PrintStream(fos);            // 输出文件的内容            ps.println(str);            ps.close();        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * 通过文件名来读取data/data/包名/files下的文件     * example:read("file.txt")     * @return      * 返回null,表示找不到文件,或出现异常     */    public static String read(Context mContext,String fileName) {        try {            // 打开文件输入流            FileInputStream fis = mContext.openFileInput(fileName);            byte[] buff = new byte[1024];            int hasRead = 0;            StringBuilder sb = new StringBuilder("");            // 读取文件内容            while ((hasRead = fis.read(buff)) > 0) {                sb.append(new String(buff, 0, hasRead));            }            // 关闭文件输入流            fis.close();            return sb.toString();        }         catch(FileNotFoundException e) {            e.printStackTrace();        }        catch (Exception e) {            e.printStackTrace();        }        return null;    }}

 

用IO流向存储器或SD卡中存入/读取字符的工具类