Android書き込みファイルの読み込み方法

2901 ワード

参照先:https://blog.csdn.net/harry_helei/article/details/64910713
1.指定ファイルを行ごとに読み込む
    /**
    *          ,   ArrayList
    */
    public static void readDataFromFile(String fileName) {
        if (fileName == null) return;

        File file = new File("/storage/emulated/0/" + fileName);//          
        if (file.isDirectory()) {
            System.out.println(fileName + " is directory");
            return;
        } else {
            try {
                InputStream inputStream = new FileInputStream(file);
                if (is != null) {
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream );
                    BufferedReader bfReader= new BufferedReader(inputStreamReader );
                    String strLine;
                    List strList = new ArrayList();
                    while ((strLine= bfReader.readLine()) != null) {
                        System.out.println(strLine);
                        strList.add(strLine);//   strList ,      
                    }
                }
            } catch (FileNotFoundException e) {
                System.out.println(fileName + " doesn't found!");
            } catch (IOException e) {
                System.out.println(fileName + " read exception, " + e.getMessage());
            }
        }
    }

2.指定ファイルへのデータの書き込み
    /**
     *              
     *
     * @param str 
     */
    public static void saveFile(String str, String fileName) {
        //   String         
        try {
            //          
            File file = new File(Environment.getExternalStorageDirectory(), fileName);
            //        
            if (file.exists()) {
                //        
                if (file.delete()) {
                    System.out.println("success");
                }
            }
            if (file.createNewFile()) {
                //           
                FileOutputStream outStream = new FileOutputStream(file);
                //         byte        
                outStream.write(str.getBytes());
                //          
                outStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * write data to txt
     */
    public static void writeStringToTxt(byte[] array, String fileName) throws IOException {
        //  1 、  File       
        File f = new File("/storage/emulated/0/" + File.separator + fileName);    //   File  
        //  2 、           
        Writer out;    //           
        out = new FileWriter(f, true);    //        ,     
        //  3 、     
        String str = new String(array) + "
"; out.write(str);// , // 4 、 out.close();// }