BufferedReader 字符输入流
此流为字符缓冲流,他是一个处理流,可以从字符输入流中读取文本,缓冲各个字符;提供了readLine()方法,可以从流中一次一行的读取文本;
使用步骤如下:
1.先创建一个节点流。
2.创建一个缓冲流,对节点流进行包装;
3.使用readLine()读取文本;
4.关闭缓冲流即可。
// 字节流
private BufferedReader bufferedReader;
@Override
public void run() {
Log.e(TAG, "run: " + Thread.currentThread().getName());
try {
// 字节流
InputStream inputStream = getResources().openRawResource(R.raw.read);
// 字符流
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"GBK");
// 带缓存的字符流
bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine())!=null){
Log.e(TAG, str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
https://blog.csdn.net/ai_bao_zi/article/details/81133476
OutputStream 字节输出流
1.先创建一个输出流
2.写入数据
3.关闭输出流
try {
FileOutputStream fileOutputStream = new FileOutputStream(path);
fileOutputStream.write("天门中断楚江开,碧水东流至此回。".getBytes(StandardCharsets.UTF_8));
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
bufferOutputStream
BufferedOutputStream的flush和close方法的区别
* flush()方法
* 1.用来刷新缓冲区,刷新后可以再次写出
* close()方法
* 2.用来关闭流释放资源
* 3.如果是带缓冲区的流对象的close()方法,不但会关闭流,还会在关闭流之前刷新缓冲区,关闭之后不能再写入
原文链接
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String currentTime = sdf.format(new Date());
String dataDir = context.getApplicationInfo().dataDir;
File f = new File(dataDir + "/logcat-" + currentTime + ".log");
if (!f.exists()) {
Log.e(TAG, "file not exist!!! ");
try {
f.getParentFile().mkdir();
} catch (Exception e) {
}
}
String path = dataDir + "/logcat-" + currentTime + ".log";
Log.e(TAG, "path: " + path);
try {
FileOutputStream fileOutputStream = new FileOutputStream(path);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bufferedOutputStream.write("天门中断楚江开,碧水东流至此回。".getBytes(StandardCharsets.UTF_8));
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}