首页 > 其他分享 >常见IO流的使用与实践

常见IO流的使用与实践

时间:2024-09-01 12:36:06浏览次数:2  
标签:1024 字节 常见 实践 length IO new byte datas

IO流

概念梳理

字节流:是让计算机读写的,让计算机理解的内容,JAVA中的Byte等同于计算机中的字节

字符流:是让人读懂的,需要指定的编码格式将字节转为字符

编码:将字符通过指定的编码格式转为字节

解码:将字节通过指定的编码格式转为字符

Java中字节流、字符流的超类

InputStream、OutputStream、Reader、Writer

字节流用来处理二进制文件(图片、MP3、视频文件),字符流用来处理文本文件

使用案例

将外部文件读取并输出到另外一个文件

1.使用字节流

try (FileInputStream in = new FileInputStream("C:\\Users\\patry-abu\\Desktop\\临时文件\\StreamDemo.java");
     FileOutputStream out = new FileOutputStream("C:\\Users\\patry-abu\\Desktop\\StreamDemo.java");) {
    // datas充当的角色是一个中间桥梁
    byte[] datas = new byte[1024];
    int length;
    while ((length = in.read(datas, 0, datas.length)) != -1) {
        out.write(datas, 0, length);
    }
}

以下通过直接读取datas.lenth长度文件不可取,原因是read(byte b[], int off, int len) 每次读取的字节书要求是len长度的内容,如果不是则会往前推直至到1024个字节,即会读取到就得数据信息举例:比如一个文件内容有1025个字节,每次读取len=1024个字节数,第一次能正常读,第二次发现不足1024个字节,则会将从最后一个字节往前推1024个字节,即第二次拿到的数据是从2-1025,两次读取过程中从2到1024个字节是重复的字节内容

try (FileInputStream in = new FileInputStream("C:\\Users\\patry-abu\\Desktop\\临时文件\\StreamDemo.java");
     FileOutputStream out = new FileOutputStream("C:\\Users\\patry-abu\\Desktop\\StreamDemo.java");) {
    // datas充当的角色是一个中间桥梁
    byte[] datas = new byte[200];
    while (in.read(datas, 0, datas.length) != -1) {
        out.write(datas, 0, datas.length);
    }
}

2.使用字符流

try (FileReader fileReader = new FileReader("原路径\\测试.txt");
     FileWriter fileWriter = new FileWriter("目的路径\\测试.txt");) {
    char[] datas = new char[1024];
    int len;
    while ((len = fileReader.read(datas, 0, datas.length)) != -1) {
        fileWriter.write(datas, 0, len);
    }
}

3.使用缓冲流输出文件

@Test
public void testFile() throws IOException {

    try (BufferedInputStream bufferedInputStream
                 = new BufferedInputStream(new FileInputStream("C:\\Users\\patry-abu\\Desktop\\金字塔原理.pdf"));
         BufferedOutputStream bufferedOutputStream
                 = new BufferedOutputStream(new FileOutputStream("C:\\Users\\patry-abu\\Desktop\\a.pdf"))) {

        int length;
        byte[] bytes = new byte[2 * 1024];
        while ((length = bufferedInputStream.read(bytes)) != -1) {
            bufferedOutputStream.write(bytes, 0, length);
        }
    }
}

5.使用内存输出流保存字节流

@Test
public void testFile() throws IOException {

    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("C:\\Users\\patry-abu\\Desktop\\b.pdf"));

    try (BufferedInputStream bufferedInputStream
                 = new BufferedInputStream(new FileInputStream("C:\\Users\\patry-abu\\Desktop\\金字塔原理.pdf"));
         // 通过内存输出流保存读取到的字节数据
         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ) {
        int length;
        byte[] bytes = new byte[2 * 1024];
        while ((length = bufferedInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, length);
        }

        byte[] fileBytes = outputStream.toByteArray();
        bufferedOutputStream.write(fileBytes);
        // 清除内存输出流
        outputStream.reset();
    }
}

6.使用HttpServletResponse输出到页面json数据

  • 使用字符流PrintWriter
public void write(HttpServletResponse response) {
    try {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf8");
        PrintWriter writer = response.getWriter();
        HashMap<String, Object> data = new HashMap<>(4);
        data.put("code", 0);
        data.put("meg", "成功");
        Gson gson = new Gson();
        writer.print(gson.toJson(data));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
  • 使用字节流OutputStream
public void write(HttpServletResponse response) {
    try {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf8");
        ServletOutputStream outputStream = response.getOutputStream();
        HashMap<String, Object> data = new HashMap<>(4);
        data.put("code", 0);
        data.put("meg", "成功");
        Gson gson = new Gson();
        outputStream.write(gson.toJson(data).getBytes(StandardCharsets.UTF_8));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

标签:1024,字节,常见,实践,length,IO,new,byte,datas
From: https://www.cnblogs.com/party-abu/p/18391186

相关文章

  • PoLLMgraph: Unraveling Hallucinations in Large Language Models via State Transit
    本文是LLM系列文章,针对《PoLLMgraph:UnravelingHallucinationsinLargeLanguageModelsviaStateTransitionDynamics》的翻译。PoLLMgraph:通过状态转换动力学揭示大型语言模型中的幻觉摘要1引言2相关工作3PoLLMgraph4实验5结论局限性摘要尽管近......
  • 【题解】Solution Set - NOIP2024模拟赛4
    【题解】SolutionSet-NOIP2024模拟赛4https://www.becoder.com.cn/contest/5501T2沉默乐团https://www.becoder.com.cn/submission/2593352T3深黯「军团」记录一下考场思路:首先对于长度为\(n\)所有排列,按顺序求出她的逆序对数量。然后找到了规律。后面基于此,写出......
  • JavaScript中的`event.preventDefault()`和`event.stopPropagation()`有什么区别?
    在JavaScript中,event.preventDefault()和event.stopPropagation()是两个常用于事件处理的重要方法,它们各自扮演着不同的角色,在控制Web页面交互行为时发挥着关键作用。下面将详细阐述这两个方法的区别,包括它们的作用、使用场景以及影响。一、event.preventDefault()1.定义与......
  • eureka原理与实践简单介绍
    目录@[TOC](目录)前言一、Eureka原理二、Eureka实践总结前言Eureka是Netflix开发的一个服务发现框架,广泛应用于微服务架构中。它通过提供服务的自动注册与发现机制,简化了服务间的依赖管理,提高了系统的灵活性和可扩展性。以下将从Eureka的原理和实践两个方面进行详细......
  • 基于Python的机器学习系列(18):梯度提升分类(Gradient Boosting Classification)
    简介        梯度提升(GradientBoosting)是一种集成学习方法,通过逐步添加新的预测器来改进模型。在回归问题中,我们使用梯度来最小化残差。在分类问题中,我们可以利用梯度提升来进行二分类或多分类任务。与回归不同,分类问题需要使用如softmax这样的概率模型来处理类别标......
  • Vue面试常见知识总结2——spa、vue按需加载、mvc与mvvm、vue的生命周期、Vue2与Vue3区
    SPASPA(SinglePageApplication,单页面应用)是一种Web应用程序架构,其核心特点是在用户与应用程序交互时,不重新加载整个页面,而是通过异步加载页面的局部内容或使用JavaScript动态更新页面。以下是对SPA的详细解析,包括其优点和缺点:SPA的优点更好的用户体验:SPA无需重新加载......
  • Burp Suite Professional 2024.8 发布下载,新增功能概览
    BurpSuiteProfessional2024.8(macOS,Linux,Windows)-Web应用安全、测试和扫描BurpSuiteProfessional,Test,find,andexploitvulnerabilities.请访问原文链接:https://sysin.org/blog/burp-suite-pro/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.orgBur......
  • 企业架构设计之IFW实践回顾
    企业架构设计之IFW实践回顾 前言笔者几年前曾参与过一套网络银行的系统建设以及后续这套系统在信用、云服务、保险、基金、支付等领域的复用,使用了IFW模型的变体。当时仅仅是根据架构师的设计进行编码、测试和交付以及后续的维护,没有对这套模型进行系统化的总结,心中总是......
  • #Datawhale #AI夏令营 #Mobile Agent 设计与实践 (2)
    系列文章目录Task1:第一篇文章Task2(loading…)Task3(loading…)Task2文章目录前言一、创新场景的idea1.股票小助手2.群聊小助手3.壁纸生成助手4.桌面整理大师二、Mobile-Agent扩展初步实践*step1:controller修改**step2:Prompt修改**step3:主文件......
  • 社会实践实习报告还没写?推荐这款AI工具,一键高效生成
    随着科技的飞速发展人工智能逐渐渗透到各个领域为咱们的工作和学带来了极大的便利。在撰写社会实践实报告这一环节一款名为“锐智AI”的一键生成工具应运而生它以其高效、智能的特点成为了广大学生和职场人士的得力助手。本文将详细介绍锐智AI助手的功能、优势以及采用方法帮......