Java IO流学习笔记

Java IO分类

Android经常涉及到文件读写到sd卡的IO操作,今天看了几篇博客,学习了一下.

参考博客如下:

深入理解Java中的IO

Java中IO流,输入输出流概述与总结

IO流上:概述、字符流、缓冲区(java基础)

按输入输出:

  • InputStream,Reader
  • OutPutStream,Writer

按操作数据分:

  • 字节流 InputSteam,OutputStream 
  • 字符流 Reader,Writer

继承关系:

InputStream,OutputStream,Reader,Writer是基类,继承关系如下图:

字符流用来处理文本数据,字节流用来操作媒体数据

流的选择很简单,可以用txt打开的用字符流,用记事本打开乱码的用字节流

 

缓冲流:

字符流和字节流都包含缓冲流,缓冲流可以提高读写效率

缓冲字符流:

BufferedWriter和BufferedReader

可以提高速度,一次可以读一行readLine()

readLine()只返回回车符前面的字符,不返回回车符。如果是复制的话,必须加入newLine(),写入回车符

缓冲字节流:

BufferedInputStream和BufferedOutputStream

以下是Demo

package demo.ad.com.iodemo;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    private boolean sdCardAvailable() {
        //创建一个txt文件用于字符流复制
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //判断是否有sd卡
            return true;
        }
        return false;
    }

    /**
     * FileWriter的使用
     * 在硬盘创建一个文件并且写入一些文字数据
     * 1.创建一个FileWriter对象
     * 2.调用write方法写入数据
     * 3.刷新对象缓冲中的数据
     * 4.关闭流
     * flush和close的区别:flush后还可以继续写入数据,close后不可以继续写入数据
     */
    private void copy1() {
        try {
            //D盘下创建文件1.txt,如果有同名文件则覆盖
            FileWriter fileWriter = new FileWriter("D:\\1.txt");
            //对已有文件1.txt读写,true代表不覆盖
            FileWriter fileWriter2 = new FileWriter("D:\\1.txt", true);
            fileWriter.write("测试数据1");
            fileWriter.flush();
            //flush后可以继续写入数据
            fileWriter.write("再次写点数据玩");
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * FileReader的使用
     * 读取数据且一次读取一个数组
     * 1.创建一个FileReader
     * 2.创建一个数组
     * 3.创建一个变量用来记录每次读取的字符个数
     * 4,读取,读取到最后一个字符时,返回-1
     * 5,关闭流
     */
    private void copy2() {
        try {
            FileReader fileReader = new FileReader("Demo.txt");
            char[] buf = new char[6];
            int num = 0;//返回的实际读取的字符个数
            while ((num = fileReader.read(buf)) != -1) {
                System.out.println(new String(buf, 0, num));
            }
            fileReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * FileReader的使用
     * 读取数据且一次读取一个字符
     * 1.创建一个FileReader
     * 2.创建一个变量用来记录每次读取的字符个数
     * 3,读取,读取到最后一个字符时,返回-1
     * 4,关闭流
     */
    private void copy3() {
        try {
            FileReader fileReader = new FileReader("Demo.txt");
            int num = 0;
            while ((num = fileReader.read()) != -1) {
                System.out.println((char) num);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 利用FileReader和FileWriter完成文件复制
     * 1.sd卡中创建文件Demo.txt,写入数据到Demo.txt中
     * 2.创建目标文件夹
     * 3.拷贝文件
     * 4.关闭流
     */
    public void copy4(View view) {
        try {
            if (sdCardAvailable()) {
                String sdPath = Environment.getExternalStorageDirectory().toString();
                String fromPath = sdPath;
                String toPahth = sdPath + "/Copy4";
                //1.sd卡中创建文件Demo.txt写入数据到Demo.txt中
                FileWriter fw = new FileWriter(fromPath + "/Demo.txt");
                fw.write("啦啦啦啦测试测试");
                fw.flush();
                fw.close();
                //2.创建目标文件夹
                File file = new File(toPahth);
                file.mkdirs();
                //3.拷贝文件
                FileReader reader = new FileReader(fromPath);
                FileWriter writer = new FileWriter(toPahth + "/Copy.txt");
                char[] chars = new char[1024];
                int num = 0;
                while ((num = reader.read(chars)) != -1) {
                    writer.write(new String(chars, 0, num));
                }
                //4.关闭流
                writer.close();
                reader.close();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 缓冲区
     * 利用BufferedWriter和BufferedReader完成文件复制
     * 1.sd卡中创建文件Demo.txt,写入数据到Demo.txt中
     * 2.创建目标文件夹
     * 3.拷贝文件 BufferedWriter BufferedReader包装FileWriter和FileReader
     * 4.关闭流
     */
    public void copy5(View view) {
        try {
            if (sdCardAvailable()) {
                String sdPath = Environment.getExternalStorageDirectory().toString();
                String fromPath = sdPath;
                String toPath = sdPath + "/Copy5";
                //1.sd卡中创建文件Demo.txt,写入数据到Demo.txt中
                FileWriter fw = new FileWriter(fromPath + "/DemoCopy5.txt");
                fw.write("copy5 测试测试哈哈哈");
                fw.flush();
                fw.close();

                //2.创建目标文件夹
                File file = new File(toPath);
                file.mkdirs();
                //3.拷贝文件 BufferedWriter BufferedReader包装FileWriter和FileReader
                FileReader reader = new FileReader(fromPath + "/DemoCopy5.txt");
                FileWriter writer = new FileWriter(toPath + "/Copy5.txt");
                BufferedWriter bufferedWriter = new BufferedWriter(writer);
                BufferedReader bufferedReader = new BufferedReader(reader);
                String s;
                while ((s = bufferedReader.readLine()) != null) {
                    bufferedWriter.write(s);
                    bufferedWriter.newLine();
                    bufferedWriter.flush();
                }
                //4.关闭流
                reader.close();
                writer.close();
                bufferedReader.close();
                bufferedWriter.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 字节流
     * 利用FileInputStream和FileOutputStream完成文件复制
     * sd卡根目录提前放了一个a.jpg,拷贝到sd卡下的Copy6目录下
     */
    public void copy6(View view) {
        try {
            if (sdCardAvailable()) {
                String sdPath = Environment.getExternalStorageDirectory().toString();
                String fromPath = sdPath;
                String toPath = sdPath + File.separator + "Copy6";
                File file = new File(toPath);
                file.mkdirs();
                FileInputStream fis = new FileInputStream(sdPath + File.separator + "a.jpg");
                FileOutputStream fos = new FileOutputStream(toPath + File.separator + "copy.jpg");
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = fis.read(bytes)) != -1) {
                    fos.write(bytes, 0, len);
                }
                fos.close();
                fis.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 高效字节流
     * 利用BufferedInputStream和BufferedOutputStream完成文件复制
     */
    public void copy7(View view) {
        try {
            if (sdCardAvailable()) {
                String sdPath = Environment.getExternalStorageDirectory().toString();
                String fromPath = sdPath;
                String toPath = sdPath + File.separator + "Copy7";
                File file = new File(toPath);
                file.mkdirs();
                FileInputStream fis = new FileInputStream(sdPath + File.separator + "a.jpg");
                FileOutputStream fos = new FileOutputStream(toPath + File.separator + "copy.jpg");

                BufferedInputStream bis = new BufferedInputStream(fis);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = bis.read(bytes)) != -1) {
                    bos.write(bytes, 0, len);
                }
                fos.close();
                fis.close();
                bis.close();
                bos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="demo.ad.com.iodemo.MainActivity">

    <Button
        android:id="@+id/bt_file_reader"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="6dp"
        android:onClick="copy4"
        android:text="FileReader and FileWriter"
        android:textAllCaps="false"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <Button
        android:id="@+id/bt_buf_file_reader"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="6dp"
        android:onClick="copy5"
        android:text="BufferedFileReader and BufferedFileWriter"
        android:textAllCaps="false"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/bt_file_reader"/>

    <Button
        android:id="@+id/bt_inputstream"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="6dp"
        android:onClick="copy6"
        android:text="InputStream and InputOutStream"
        android:textAllCaps="false"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/bt_buf_file_reader"/>

    <Button
        android:id="@+id/bt_buf_inputstream"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="6dp"
        android:onClick="copy7"
        android:text="BufferedInputStream and BufferedInputOutStream"
        android:textAllCaps="false"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/bt_inputstream"/>

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="347dp"
        android:layout_height="212dp"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        tools:layout_editor_absoluteY="242dp"/>

</android.support.constraint.ConstraintLayout>

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值