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 @   lai_xinghai  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示