文件的读取与写入

此文章主要是通过流将文件的内容读取出来和将上传的文件保存到本地(还有不足之处,后续更新)

一、文件的读取

注:方法参数为文件路径+文件全名(例:D:\fileReader\file.json)
/**
 * 读取文件内容
 * @param fileName 文件的本地路径(文件路径+文件全名)
 * @return 文件内容
 */
public static String readJsonFile(String fileName) {
    String jsonStr = "";
    try {
    // 获取文件对象
    File file = new File(fileName);
    if (!file.getParentFile().exists()) {// 如果父目录不存在,创建父目录
        file.getParentFile().mkdirs();
    }
    if (file.exists()) {// 当文件存在时进行文件的读取
        System.out.println("文件的本地路径:" + fileName);
        // 获取文件的字节输入流并指定编码
        Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
        int ch = 0;
        StringBuffer sb = new StringBuffer();
        while ((ch = reader.read()) != -1) {// 通过流读取文件内容,读取为-1时读取完成
            sb.append((char) ch);
        }
        reader.close();
        jsonStr = sb.toString();// 将读取的内容转换为字符串
    } else {// 当文件不存在时创建一个内容为空的文件(前提是有父目录,上面已经创建好了)
        file.createNewFile();
    }
    return jsonStr;// 将读到的文件内容进行返回
    } catch (IOException e) {
    e.printStackTrace();
    return null;
    }
}

二、文件的保存

注:方法的参数为前端传过来的文件
/**
 * 文件的上传
 *
 * @param file 前端传过来的文件
 * @return 旧文件名、新文件名、文件保存的路径、异常
 */
public Map<String, String> fileWriter(MultipartFile file) {
    // 返回的信息
    Map<String, String> map = new HashMap<>();
    if (file.isEmpty()) {
        map.put("error", "上传的文件不能为空");
        return map;
    }
    try {
        // 得到文件的原始名
        String oldName = file.getOriginalFilename();
        // 得到文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        // 上传文件
        // file.getinputstream()的作用是获取文件的输入流,可以用来读取文件的内容;
        InputStream stream = file.getInputStream();
        // inputstream.available() 方法是用于检测从输入流中读取的字节数。
        // 返回值是可以在当前时间读取的字节数。如果返回值是 0,则说明没有可用的字节可以读取。
        byte[] bytes = new byte[stream.available()];
        stream.read(bytes);//每次读取数据放到bytes数组,返回读取到数据的有效个数,读取到文件末尾返回-1。
        // 生成UUID,拼接新的文件名、文件路径
        String uuid = UUIDUtil.getUUID();
        String newName = uuid + suffix;
        String url = "D:\\fileWriter\\";
        String path = url + newName;
        // 获取文件对象
        File newFile = new File(path);
        // 获得文件的父级目录
        File parent = newFile.getParentFile();
        if (!parent.exists()) {// 如果父目录不存在,创建父目录
            parent.mkdirs();
        }
        if (!newFile.exists()) {// 把图片保存到路径中(暂时只能上传图片,上传其他后续更新)
            file.transferTo(newFile);
        }
        System.out.println("文件上传成功:" + newName);
        map.put("oldFileName", oldName);
        map.put("newFileName", newName);
        map.put("newFilePath", path);
    } catch (IOException e) {
        map.put("error", "上传失败!");
        e.printStackTrace();
        return map;
    }
    return map;
}
注:读取文件转换为Base64并返回,代码如下
{// 读取文件转换为Base64并返回
    String url = “C:\Users\Administrator\Desktop\小马\11.jpg”;
    ByteArrayOutputStream baos = null;
    try {
        //获取图片类型
        String suffix = url.substring(url.lastIndexOf(".") + 1);
        //构建文件
        File imageFile = new File(url);
        //通过ImageIO把文件读取成BufferedImage对象
        BufferedImage bufferedImage = ImageIO.read(imageFile);
        //构建字节数组输出流
        baos = new ByteArrayOutputStream();
        //写入流
        ImageIO.write(bufferedImage, suffix, baos);
        //通过字节数组流获取字节数组
        byte[] bytes = baos.toByteArray();
        //获取JDK8里的编码器Base64.Encoder转为base64字符
        String str = Base64.getEncoder().encodeToString(bytes);
        return str;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (baos != null) {
                baos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

UUID的获取,代码如下:

/**
 * 生成uuid
 * @return UUID
 */
public static String getUUID() {
    String id = UUID.randomUUID().toString();
    // 自动生成的UUID会自带符号‘-’,将符号替换成空串
    // 替换前:3cc7bebf-87be-4e96-971f-025ecec185c0
    // 替换后:3cc7bebf87be4e96971f025ecec185c0
    id = id.replace("-", "");
    return id;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

i源

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值