用IO流进行文件读写的封装工具类

第一次发博客,谢谢支持~~~

import android.os.Environment;


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/28.
 */

public class FileUtils {
    //获取sd卡绝对路径
    private static String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    public static File file = new File(path, "up.txt");
    public static String sp = "------";

    public static void writeup(String str, boolean b) {

        if (!file.isDirectory()) {
            //内存输入字节流
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(str.getBytes());
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(file, b);
                int len = 0;
                byte[] buffer = new byte[1024];
                while ((len = byteArrayInputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, len);
                }
                byteArrayInputStream.close();
                fileOutputStream.close();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 一个蠢萌蠢萌的读取文本的方法
     */
    public static List readstr(File file) {
        ArrayList strings = new ArrayList<>();
        if (file.exists() && !file.isDirectory()) {
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
//                int len = 0;
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
                String read = "";
                while ((read = bufferedReader.readLine()) != null) {
                    strings.add(read);
                }
                bufferedReader.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return strings;
    }

    /***
     * 分割的方法
     */
    public static String[] getstr(String str) {
        //123213
        String[] strings = new String[2];
        if (str.length() > sp.length() + 1) {
            int i = str.indexOf("-");
            if (i != -1) {
                String substring = str.substring(0, i);
                strings[0] = substring;
            }
            int i1 = str.lastIndexOf("-");
            if (i1 != -1) {
                String substring = str.substring(i1 + 1, str.length());
                strings[1] = substring;
            }
        }
        return strings;
    }

}

指导老师:张志伟


你可能感兴趣的:(用IO流进行文件读写的封装工具类)