Java基础 字节流、字符流( 三 )


构造举例 , 代码如下:
public class FileInputStreamConstructor throws IOException{ public static void main(String[] args) {// 使用File对象创建流对象File file = new File("a.txt");FileInputStream fos = new FileInputStream(file);// 使用文件名称创建流对象FileInputStream fos = new FileInputStream("b.txt");}}读取字节数据

  1. 读取字节: read 方法 , 每次可以读取一个字节的数据 , 提升为int类型 , 读取到文件末尾 , 返回 -1  , 代码使 用演示:
public class FISRead {public static void main(String[] args) throws IOException{// 使用文件名称创建流对象FileInputStream fis = new FileInputStream("read.txt");// 读取数据 , 返回一个字节int read = fis.read(); System.out.println((char) read); read = fis.read(); System.out.println((char) read); read = fis.read(); System.out.println((char) read); read = fis.read(); System.out.println((char) read); read = fis.read(); System.out.println((char) read);// 读取到末尾,返回‐1read = fis.read(); System.out.println( read);// 关闭资源fis.close();}}输出结果:a b c d e‐1循环改进读取方式 , 代码使用演示:
public class FISRead {public static void main(String[] args) throws IOException{// 使用文件名称创建流对象FileInputStream fis = new FileInputStream("read.txt");// 定义变量 , 保存数据int b ;// 循环读取while ((b = fis.read())!=‐1) { System.out.println((char)b);}// 关闭资源fis.close();}}输出结果:a b c d e小贴士:
虽然读取了一个字节 , 但是会自动提升为int类型 。
流操作完毕后 , 必须释放系统资源 , 调用close方法 , 千万记得 。
2. 使用字节数组读取: read(byte[] b)  , 每次读取b的长度个字节到数组中 , 返回读取到的有效字节个数 , 读 取到末尾时 , 返回 -1  , 代码使用演示:
public class FISRead {public static void main(String[] args) throws IOException{// 使用文件名称创建流对象.FileInputStream fis = new FileInputStream("read.txt"); // 文件中为abcde// 定义变量 , 作为有效个数int len ;// 定义字节数组 , 作为装字节数据的容器byte[] b = new byte[2];// 循环读取while (( len= fis.read(b))!=‐1) {// 每次读取后,把数组变成字符串打印System.out.println(new String(b));}// 关闭资源fis.close();}}输出结果:ab cd ed错误数据 d  , 是由于最后一次读取时 , 只读取一个字节 e  , 数组中 , 上次读取的数据没有被完全替换 , 所以要通 过 len  , 获取有效的字节 , 代码使用演示:
public class FISRead {public static void main(String[] args) throws IOException{// 使用文件名称创建流对象.FileInputStream fis = new FileInputStream("read.txt"); // 文件中为abcde// 定义变量 , 作为有效个数int len ;// 定义字节数组 , 作为装字节数据的容器byte[] b = new byte[2];// 循环读取while (( len= fis.read(b))!=‐1) {// 每次读取后,把数组的有效字节部分 , 变成字符串打印System.out.println(new String(b , 0 , len));// len 每次读取的有效字节个数}// 关闭资源fis.close();}}输出结果:ab cd e小贴士:
使用数组读取 , 每次读取多个字节 , 减少了系统间的IO操作次数 , 从而提高了读写的效率 , 建议开发中使 用 。
2.6字节流练习:图片复制
复制原理图解
Java基础 字节流、字符流

文章插图
 
案例实现
复制图片文件 , 代码使用演示:
public class Copy {public static void main(String[] args) throws IOException {// 1.创建流对象// 1.1 指定数据源FileInputStream fis = new FileInputStream("D:test.jpg");// 1.2 指定目的地FileOutputStream fos = new FileOutputStream("test_copy.jpg");// 2.读写数据// 2.1 定义数组byte[] b = new byte[1024];// 2.2 定义长度int len;// 2.3 循环读取while ((len = fis.read(b))!=‐1) {// 2.4 写出数据fos.write(b, 0 , len);}// 3.关闭资源fos.close();fis.close();}}小贴士:
流的关闭原则:先开后关 , 后开先关 。
第三章 字符流当使用字节流读取文本文件时 , 可能会有一个小问题 。就是遇到中文字符时 , 可能不会显示完整的字符 , 那是因为 一个中文字符可能占用多个字节存储 。所以Java提供一些字符流类 , 以字符为单位读写数据 , 专门用于处理文本文 件 。


推荐阅读