Blocking IO的常见用例

BufferedReader(字符读入处理流)读取文件中的内容

BufferReader适合需要对文件中的内容进行处理的情况

private StringBuilder getFileContent(MultipartFile oneFile) {//MultipartFile是spring文件上传的工具类
        StringBuilder fileContent = new StringBuilder("");
        //try-with-resource,将自动关闭resource(前提是其中的类实现AutoCloseable接口)
        try (InputStream is = oneFile.getInputStream()
             ; InputStreamReader isr = new InputStreamReader(is, "gb2312")//gb2312是win下txt编码模式
             ; BufferedReader br = new BufferedReader(isr)
        ) {
            String temp = null;     //用于接收每读一行的内容
            while ((temp = br.readLine()) != null) {    //null判断文件读取是否结束,不能用temp的长度判断
                fileContent.append(temp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileContent;
    }

try-with-resource相关语法可参考

当只需要对文件进行输入输出时,可以使用字节节点流(如FileInputStream、FileOutputStream)

private void writeFile(MultipartFile multipartFile, String path) throws IOException {
        // 如果没有文件上传,MultipartFile也不会为null,可以通过调用getSize()方法获取文件的大小来判断是否有上传文件
        if (multipartFile.getSize() <= 0) {
            return;
        }
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
            System.out.println(file.getPath() + "不存在,现已被创建");
        }
        file = new File(path, multipartFile.getOriginalFilename());
        //下面两行语句都可以完成文件的写入,且都是使用的字节节点流
//        multipartFile.transferTo(file);
//org.apache.commons.io.IOUtils,其方法体的主要内容参考下面的copyLarge
        IOUtils.copy(multipartFile.getInputStream(),new FileOutputStream(file));
    }
//copy方法的主要内容。buffer为读入缓存数组的大小
public static long copyLarge(final InputStream input, final OutputStream output, final byte[] buffer)
            throws IOException {
        long count = 0;
        int n;
        while (EOF != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

发布了91 篇原创文章 · 获赞 54 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/BigBug_500/article/details/103446743