一 使用字节流读数据

read() 优化:使用死循环

 FileInputStream fis = new FileInputStream("D:\\\\aaa.txt");
    int a;
    while((a=fis.read())!=-1){
        System.out.println((char)a);
    }
    fis.close();

read(byte[] bytes)

  FileInputStream fis = new FileInputStream("D:\\aaa.txt");
    int a;
    byte[] bytes = new byte[1024];
    while((a=fis.read(bytes))!=-1){
        //String(byte[] bytes,int offseet,int length)通过使用平台的默认字符集解码指定的字节子阵列来构造新的 String 。 
        String  str = new String(bytes,0,a);
        System.out.println(str);
    }
    fis.close();

二 使用字节流写数据

read(byte[] bytes)

 FileOutputStream fos = new FileOutputStream("D:\\aaa.txt");
    String  str = "abc";
    //String类中的方法 Byte[] getBytes()  将String——>byte,存到数组中
    byte[] bytes = str.getBytes();
    fos.write(bytes);
    fos.close();

三 文件复制

1 创建字节输入流对象,关联源文件
2 创建字节输出流对象,关联目标文件
3 循环进行读、写动作
4 释放资源

FileInputStream fis = new FileInputStream("D:\\aaa.txt");
    FileOutputStream fos = new FileOutputStream("D:\\aaa(fuzhi).txt");
    int a;
    byte[] bytes = new byte[1024];
    while((a=fis.read(bytes))!=-1){
        fos.write(bytes,0,a);
    }
        fis.close();
        fos.close();

拓展

编码:按照某种规则,将字符存储到计算机中
解码:将存储在计算机中的二进制数按照某种规则解析显示出来
ASCII GBK UTF-8

  • UTF-8编码,一个中文占3个字节,数字、字母、标点占1个字节
  • GBK编码,一个中文占2个字节,数字、字母、标点占1个字节
  • 换行 fos.write( "\r\n".getBytes());

1 编码

byte[] getBytes() 将String——>byte,结果存到数组中
byte[] getBytes(String charsetName) 使用指定字符集

2 解码

String(byte[] bytes) 将byte——>String
String(byte[] bytes,String charsetName)

验证字符集

Charset.defaultCharset()