文件读写等操作

最后都变了- 提交于 2020-02-27 07:00:55

                                              文件相关操作

1、读文件,一行一行的读

public static void readFile(File file) {
        InputStream instream = null;
        try {
            instream = new FileInputStream(file);

            if (instream != null) {
                InputStreamReader inputreader = new InputStreamReader(instream);
                BufferedReader buffreader = new BufferedReader(inputreader);

                String line;

                //分行读取
                while ((line = buffreader.readLine()) != null) {
                    Log.d("readFile: line str = ", line);
                }
            }
        } catch (java.io.FileNotFoundException e) {
            Log.d("readFile", "The File doesn't exist.");
        } catch (IOException e) {
            Log.d("readFile", e.getMessage());
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {

            }
        }
    }

2、一行一行的写

private void writeFile(File file) {
        FileOutputStream fileOutputStream = null;

        try {
            fileOutputStream = new FileOutputStream(file);
            List<String> strList = new ArrayList<>();

            strList.add("string 1");
            strList.add("string 2");
            strList.add("string 3");
            strList.add("string 4");
            strList.add("string 5");
            strList.add("string 6");

            for (String str : strList) {
                String writeLine = str + "\n";
                fileOutputStream.write(writeLine.getBytes());
            }
        } catch (java.io.FileNotFoundException e) {

        } catch (IOException e) {
            Log.d(TAG, "writeFile" + e.getMessage());
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {

            }
        }
    }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!