java中IO流字节的读入与复制操作

import java.io.*;import org.junit.Test;

/*
 * FileInputStream和FileOutputStream的使用
 */
public class FileInputOutputStreamTest {
    
    // 使用字节流FileInputStream处理文本文件,可能出现乱码
    @Test
    public void testFileInputStream() {
        FileInputStream fis = null;
        try {
            // 1.实例化File类的对象,指明要操作的文件
            File file = new File("hello.txt");
            
            // 2.造流
            fis = new FileInputStream(file);
            
            // 3.1读数据
            // read():返回读入的一个字符。如果文件末尾,返回-1
//            int data;
//            while ((data = fis.read()) != -1) {
//                // 转换为char类型的才能正常显示
//                System.out.print((char)data);
//            }
            
            // 3.2读数据(因为是字节流这边造一个字节数组)
            byte[] buffer = new byte[5];
            int len; // 记录每次读取的字节的个数
            while ((len = fis.read(buffer)) != -1) {
                // 遍历数组一:用String构造器
                String str = new String(buffer,0,len);
                System.out.print(str);
                // 遍历数组二:
//                for (int i = 0; i < len; i++) {
//                    System.out.print((char)buffer[i]);
//                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fis != null) {
                // 4.关闭资源
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    // 复制非文本文件
    @Test
    public void testOutputStream() {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("飘窗.jpg");
            fos = new FileOutputStream("飘窗1.jpg");
            // 读入后写出数据
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {// 4.关闭资源
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

posted @ 2022-09-21 09:00  lai_xinghai  阅读(31)  评论(0)    收藏  举报