Android file

写文件——FileOutputStream openFileOutput
读文件——FileInputStream openFileInput
openFileOutput写文件时当文件不存在,Android自动创建。

通过BufferedWriter直接写入字符串

public void writeFile(String inputText) {
    FileOutputStream outputStream = null;
    BufferedWriter writer = null;
    try {
        outputStream = openFileOutput("location", Context.MODE_APPEND);
        writer = new BufferedWriter(new OutputStreamWriter(outputStream));
        writer.write(inputText);
    } catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        try {
            if(writer != null) {
                writer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

通过FileOutputStream也可直接写入内容此时要转成buty[]
MODE_APPEND:每次追加内容
MODE_PRIVATE:每次覆盖内容

outputStream = openFileOutput("location", Context.MODE_APPEND);
outputStream.write(inputText.getBytes());

通过BufferedReader读取文件内容

public String readFile() {
    FileInputStream inputStream = null;
    BufferedReader reader = null;
    StringBuilder content = new StringBuilder();
    try {
        inputStream = openFileInput("location");
        reader = new BufferedReader(new InputStreamReader(inputStream));
        String text = "";
        while ((text = reader.readLine()) != null) {
            content.append(text);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return content.toString();
}

你可能感兴趣的:(Android,android,前端)