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(); } } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统