java流处理

82 篇文章 1 订阅

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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学知识拯救世界

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值