Java Code Examples for cn.hutool.core.io.IoUtil#close()

The following examples show how to use cn.hutool.core.io.IoUtil#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileUtils.java    From sk-admin with Apache License 2.0 6 votes vote down vote up
/**
 * 导出excel
 */
public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
    String tempPath =System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx";
    File file = new File(tempPath);
    BigExcelWriter writer= ExcelUtil.getBigWriter(file);
    // 一次性写出内容,使用默认样式,强制输出标题
    writer.write(list, true);
    //response为HttpServletResponse对象
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
    //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
    response.setHeader("Content-Disposition","attachment;filename=file.xlsx");
    ServletOutputStream out=response.getOutputStream();
    // 终止后删除临时文件
    file.deleteOnExit();
    writer.flush(out, true);
    //此处记得关闭输出Servlet流
    IoUtil.close(out);
}
 
Example 2
Source File: ScriptProcessBuilder.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 结束执行
 *
 * @param msg 响应的消息
 */
private void end(String msg) {
    if (this.process != null) {
        // windows 中不能正常关闭
        this.process.destroy();
        IoUtil.close(inputStream);
        IoUtil.close(errorInputStream);
    }
    Iterator<Session> iterator = sessions.iterator();
    while (iterator.hasNext()) {
        Session session = iterator.next();
        try {
            SocketSessionUtil.send(session, msg);
        } catch (IOException e) {
            DefaultSystemLog.getLog().error("发送消息失败", e);
        }
        iterator.remove();
    }
    FILE_SCRIPT_PROCESS_BUILDER_CONCURRENT_HASH_MAP.remove(this.scriptFile);
}
 
Example 3
Source File: AccoutResource.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
@AnonymousAccess
@GetMapping(path = "/code/{randomStr}")
@ApiOperation(value = "获取验证码")
public void valicode(@PathVariable String randomStr, HttpServletResponse response) throws IOException {
	Assert.isTrue(StringUtil.isNotEmpty(randomStr), "机器码不能为空");
	response.setHeader("Cache-Control", "no-store, no-cache");
	response.setHeader("Transfer-Encoding", "JPG");
	response.setContentType("image/jpeg");
	//生成文字验证码
	String text = producer.createText();
	//生成图片验证码
	BufferedImage image = producer.createImage(text);
	RedisUtil.setCacheString(CommonConstants.DEFAULT_CODE_KEY + randomStr, text, CommonConstants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);
	//创建输出流
	ServletOutputStream out = response.getOutputStream();
	//写入数据
	ImageIO.write(image, "jpeg", out);
	IoUtil.close(out);
}
 
Example 4
Source File: SshService.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 下载文件
 *
 * @param sshModel   实体
 * @param remoteFile 远程文件
 * @param save       文件对象
 * @throws FileNotFoundException io
 * @throws SftpException         sftp
 */
public void download(SshModel sshModel, String remoteFile, File save) throws FileNotFoundException, SftpException {
    Session session = null;
    ChannelSftp channel = null;
    OutputStream output = null;
    try {
        session = getSession(sshModel);
        channel = (ChannelSftp) JschUtil.openChannel(session, ChannelType.SFTP);
        output = new FileOutputStream(save);
        channel.get(remoteFile, output);
    } finally {
        IoUtil.close(output);
        JschUtil.close(channel);
        JschUtil.close(session);
    }
}
 
Example 5
Source File: FileUtil.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
/**
 * 导出excel
 */
public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
    String tempPath =System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx";
    File file = new File(tempPath);
    BigExcelWriter writer= ExcelUtil.getBigWriter(file);
    // 一次性写出内容,使用默认样式,强制输出标题
    writer.write(list, true);
    //response为HttpServletResponse对象
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
    //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
    response.setHeader("Content-Disposition","attachment;filename=file.xlsx");
    ServletOutputStream out=response.getOutputStream();
    // 终止后删除临时文件
    file.deleteOnExit();
    writer.flush(out, true);
    //此处记得关闭输出Servlet流
    IoUtil.close(out);
}
 
Example 6
Source File: HdfsUtil.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
/**
 * 上传文件
 * <p>
 * 如果 {@link File}存在,读取文件内容,并上传到 targetPath
 *
 * @param file       原文件
 * @param targetPath 文件路径
 * @throws IOException
 */
public void uploadFile(@NotNull File file, @NotBlank String targetPath) throws Exception {

    if (file == null || !file.exists()) {
        throw new IOException("file not exists");
    }

    // 从文件中读取二进制数据
    byte[] bytes = IoUtil.readBytes(new FileInputStream(file));

    FileSystem fileSystem = null;
    FSDataOutputStream outputStream = null;
    try {
        fileSystem = this.hdfsPool.borrowObject();
        outputStream = fileSystem.create(new Path(targetPath));
        outputStream.write(bytes);
        outputStream.flush();
    } finally {
        IoUtil.close(outputStream);
        if (fileSystem != null) { this.hdfsPool.returnObject(fileSystem); }
    }
}
 
Example 7
Source File: HdfsUtil.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
/**
 * 上传文件
 *
 * @param inputStream 输入流
 * @param targetPath  文件路径
 * @throws IOException
 */
public void uploadFile(@NotNull InputStream inputStream, @NotBlank String targetPath) throws Exception {
    // 从输入流中读取二进制数据
    byte[] bytes = IoUtil.readBytes(inputStream);

    FileSystem fileSystem = null;
    FSDataOutputStream outputStream = null;
    try {
        fileSystem = this.hdfsPool.borrowObject();
        outputStream = fileSystem.create(new Path(targetPath));
        outputStream.write(bytes);
        outputStream.flush();
    } finally {
        IoUtil.close(outputStream);
        if (fileSystem != null) { this.hdfsPool.returnObject(fileSystem); }
    }
}
 
Example 8
Source File: HdfsUtil.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
/**
 * 复制文件
 *
 * @param sourcePath 原文件路径
 * @param targetPath 目标文件路径
 * @throws Exception
 */
public void copyFile(@NotBlank String sourcePath, @NotBlank String targetPath, int buffSize) throws Exception {
    FileSystem fileSystem = null;
    FSDataInputStream inputStream = null;
    FSDataOutputStream outputStream = null;
    try {
        fileSystem = this.hdfsPool.borrowObject();
        inputStream = fileSystem.open(new Path(sourcePath));
        outputStream = fileSystem.create(new Path(targetPath));
        if (buffSize <= 0) {
            int DEFAULT_BUFFER_SIZE = 1024 * 1024 * 64;
            buffSize = DEFAULT_BUFFER_SIZE;
        }
        IOUtils.copyBytes(inputStream, outputStream, buffSize, false);
    } finally {
        IoUtil.close(outputStream);
        IoUtil.close(inputStream);
        if (fileSystem != null) { this.hdfsPool.returnObject(fileSystem); }
    }
}
 
Example 9
Source File: SysGeneratorServiceImpl.java    From smaker with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 生成代码
 *
 * @param genConfig 生成配置
 * @return
 */
@Override
public byte[] generatorCode(GenConfig genConfig) {
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	ZipOutputStream zip = new ZipOutputStream(outputStream);

	//查询表信息
	Map<String, String> table = queryTable(genConfig.getTableName());
	//查询列信息
	List<Map<String, String>> columns = queryColumns(genConfig.getTableName());
	//生成代码
	GenUtils.generatorCode(genConfig, table, columns, zip);
	IoUtil.close(zip);
	return outputStream.toByteArray();
}
 
Example 10
Source File: ServletUtils.java    From yue-library with Apache License 2.0 5 votes vote down vote up
/**
 * 返回数据给客户端
 * 
 * @param text 返回的内容
 * @param contentType 返回的类型
 */
public static void write(String text, String contentType) {
	HttpServletResponse response = getResponse();
	response.setContentType(contentType);
	Writer writer = null;
	try {
		writer = response.getWriter();
		writer.write(text);
		writer.flush();
	} catch (IOException e) {
		throw new UtilException(e);
	} finally {
		IoUtil.close(writer);
	}
}
 
Example 11
Source File: ServletUtils.java    From yue-library with Apache License 2.0 5 votes vote down vote up
/**
 * 返回文件给客户端
 * 
 * @param file 写出的文件对象
 * @since 4.1.15
 */
public static void write(File file) {
	final String fileName = file.getName();
	final String contentType = ObjectUtil.defaultIfNull(FileUtil.getMimeType(fileName), "application/octet-stream");
	BufferedInputStream in = null;
	try {
		in = FileUtil.getInputStream(file);
		write(in, contentType, fileName);
	} finally {
		IoUtil.close(in);
	}
}
 
Example 12
Source File: ServletUtils.java    From yue-library with Apache License 2.0 5 votes vote down vote up
/**
 * 返回数据给客户端
 * 
 * @param in 需要返回客户端的内容
 * @param bufferSize 缓存大小
 */
public static void write(InputStream in, int bufferSize) {
	ServletOutputStream out = null;
	try {
		out = getResponse().getOutputStream();
		IoUtil.copy(in, out, bufferSize);
	} catch (IOException e) {
		throw new UtilException(e);
	} finally {
		IoUtil.close(out);
		IoUtil.close(in);
	}
}
 
Example 13
Source File: SshHandler.java    From Jpom with MIT License 5 votes vote down vote up
@Override
public void destroy(WebSocketSession session) {
    try {
        if (session.isOpen()) {
            session.close();
        }
    } catch (IOException ignored) {
    }
    HandlerItem handlerItem = HANDLER_ITEM_CONCURRENT_HASH_MAP.get(session.getId());
    IoUtil.close(handlerItem.inputStream);
    IoUtil.close(handlerItem.outputStream);
    JschUtil.close(handlerItem.channel);
    JschUtil.close(handlerItem.openSession);
}
 
Example 14
Source File: HdfsUtil.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
/**
 * 读取文件内容
 *
 * @param path 文件路径
 * @return
 * @throws Exception
 */
public String readFile(@NotBlank String path) throws Exception {
    if (!exists(path)) {
        throw new IOException(path + " not exists in hdfs");
    }

    // 目标路径
    Path sourcePath = new Path(path);
    BufferedReader reader = null;
    FSDataInputStream inputStream = null;
    FileSystem fileSystem = null;
    try {
        fileSystem = this.hdfsPool.borrowObject();
        inputStream = fileSystem.open(sourcePath);
        // 防止中文乱码
        reader = new BufferedReader(new InputStreamReader(inputStream));
        String lineTxt = "";
        StringBuffer sb = new StringBuffer();
        while ((lineTxt = reader.readLine()) != null) {
            sb.append(lineTxt);
        }
        return sb.toString();
    } finally {
        IoUtil.close(reader);
        IoUtil.close(inputStream);
        if (fileSystem != null) { this.hdfsPool.returnObject(fileSystem); }
    }
}
 
Example 15
Source File: JpomApplicationEvent.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 解锁进程文件
 */
private void unLockFile() {
    if (lock != null) {
        try {
            lock.release();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    IoUtil.close(lock);
    IoUtil.close(fileChannel);
    IoUtil.close(fileOutputStream);
}
 
Example 16
Source File: DiscountCouponServiceImpl.java    From spring-cloud-shop with MIT License 4 votes vote down vote up
@Override
public Response publish(String file, Long templateId) {

    DiscountCouponTemplate template = discountCouponTemplateMapper.selectById(templateId);

    // 选择的优惠券模板可用
    if (Objects.nonNull(template)) {
        log.info("选择的优惠券模板可用 templateId = {}", templateId);
        DataInputStream inputStream = null;

        try {

            inputStream = FileUtil.getRemoteFile(file);
            // 初始设置补发优惠券的大小
            List<String> phones = Lists.newArrayList();
            Excel07SaxReader reader = new Excel07SaxReader((sheetIndex, rowIndex, rowList) -> {
                // 过滤掉标题
                if (0 != rowIndex) {
                    phones.add(rowList.get(0).toString());
                }
            });

            reader.read(inputStream, 0);

            if (CollectionUtils.isEmpty(phones)) {
                log.info("excel 文件中没有用户手机号");
                return new Response(ResponseStatus.Code.FAIL_CODE, ResponseStatus.PUBLISH_COUPON_PHONE_IS_BLANK);
            }

            UserRequest request = new UserRequest();
            request.setPhones(phones);
            // 取出正常的用户
            Response<List<UserInfoResponse>> existsResponse = userClient.isExists(request);

            List<UserInfoResponse> exists = null;
            if (ResponseStatus.Code.SUCCESS == existsResponse.getCode() && null != existsResponse.getData()) {
                exists = existsResponse.getData();
            }

            if (!CollectionUtils.isEmpty(exists)) {
                log.info("查询到用户");
                // 当前补发优惠券的人数大于1000,则采用线程方式发送
                if (exists.size() >= 1000) {
                    // 多线程执行后返回正常的插入的手机号
                    List<String> list = new ForkJoinPool(2).invoke(new SendCouponTask(exists, template, this.baseMapper));

                    // 移除发送正常的手机号码
                    phones.removeAll(list);

                } else {

                    exists.forEach(v -> {

                        DiscountCoupon discountCoupon = new DiscountCoupon();
                        discountCoupon.setUserId(v.getId());
                        discountCoupon.setTemplateId(template.getId());
                        discountCoupon.setPhone(v.getPhone());
                        discountCoupon.setUsed(Boolean.FALSE);
                        discountCoupon.setCreateTime(DateUtils.dateTime());
                        discountCoupon.setUpdateTime(DateUtils.dateTime());
                        discountCoupon.setDeleteStatus(Boolean.FALSE);

                        this.baseMapper.insert(discountCoupon);

                    });

                }

                // 最后得到的phones 存在的值必然是错误用户的手机号,这里的错误信息只提供参考,不打算存储在数据库中,放入redis中时效性7d
                if (!CollectionUtils.isEmpty(phones)) {
                    log.info("存在错误的用户手机号,存在redis中,用于给运营展示");
                    redisService.set(RedisKeys.ManageKeys.SEND_COUPON_LIST + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN), JSON.toJSONString(phones), 7 * 60 * 60 * 24);
                }
            } else {
                log.info("未查到用户");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(inputStream);
        }
    }

    return new Response();
}
 
Example 17
Source File: HdfsUtil.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
/**
 * 上传大文件
 *
 * @param sourcePath 原文件路径
 * @param targetPath 文件路径
 * @throws IOException
 */
public void uploadBigFile(@NotBlank String sourcePath, @NotBlank String targetPath) throws Exception {

    File file = new File(sourcePath);
    if (file.exists()) {
        throw new IOException("file not exists");
    }
    final float fileSize = file.length();

    FileSystem fileSystem = null;
    InputStream inputStream = null;
    FSDataOutputStream outputStream = null;
    try {
        fileSystem = this.hdfsPool.borrowObject();
        inputStream = new BufferedInputStream(new FileInputStream(file));
        outputStream = fileSystem.create(new Path(targetPath),
            new Progressable() {
                long cnt = 0;

                @Override
                public void progress() {
                    cnt++;
                    // progress 方法每上传大约 64KB 的数据后就会被调用一次
                    System.out.println("上传进度:" + (cnt * 64 * 1024 / fileSize) * 100 + " %");
                }
            });

        IoUtil.copyByNIO(inputStream, outputStream, 4096, new StreamProgress() {
            @Override
            public void start() {
                log.info("copy start");
            }

            @Override
            public void progress(long progressSize) {
            }

            @Override
            public void finish() {
                log.info("copy success");
            }
        });
    } finally {
        IoUtil.close(outputStream);
        IoUtil.close(inputStream);
        if (fileSystem != null) { this.hdfsPool.returnObject(fileSystem); }
    }
}
 
Example 18
Source File: FileTailWatcherRun.java    From Jpom with MIT License 4 votes vote down vote up
public void close() {
    this.start = false;
    IoUtil.close(this.randomFile);
}
 
Example 19
Source File: CertModel.java    From Jpom with MIT License 4 votes vote down vote up
/**
 * 解析证书
 *
 * @param key  zip里面文件
 * @param file 证书文件
 * @return 处理后的json
 */
public static JSONObject decodeCert(String file, String key) {
    if (file == null) {
        return null;
    }
    if (!FileUtil.exist(file)) {
        return null;
    }
    InputStream inputStream = null;
    try {
        inputStream = ResourceUtil.getStream(key);
        PrivateKey privateKey = PemUtil.readPemPrivateKey(inputStream);
        IoUtil.close(inputStream);
        inputStream = ResourceUtil.getStream(file);
        PublicKey publicKey = PemUtil.readPemPublicKey(inputStream);
        IoUtil.close(inputStream);
        RSA rsa = new RSA(privateKey, publicKey);
        String encryptStr = rsa.encryptBase64(KEY, KeyType.PublicKey);
        String decryptStr = rsa.decryptStr(encryptStr, KeyType.PrivateKey);
        if (!KEY.equals(decryptStr)) {
            throw new JpomRuntimeException("证书和私钥证书不匹配");
        }
    } finally {
        IoUtil.close(inputStream);
    }
    try {
        inputStream = ResourceUtil.getStream(file);
        // 创建证书对象
        X509Certificate oCert = (X509Certificate) KeyUtil.readX509Certificate(inputStream);
        //到期时间
        Date expirationTime = oCert.getNotAfter();
        //生效日期
        Date effectiveTime = oCert.getNotBefore();
        //域名
        String name = oCert.getSubjectDN().getName();
        int i = name.indexOf("=");
        String domain = name.substring(i + 1);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("expirationTime", expirationTime.getTime());
        jsonObject.put("effectiveTime", effectiveTime.getTime());
        jsonObject.put("domain", domain);
        jsonObject.put("pemPath", file);
        jsonObject.put("keyPath", key);
        return jsonObject;
    } catch (Exception e) {
        DefaultSystemLog.getLog().error(e.getMessage(), e);
    } finally {
        IoUtil.close(inputStream);
    }
    return null;
}
 
Example 20
Source File: UploadFile.java    From yue-library with Apache License 2.0 4 votes vote down vote up
/**
 * 处理上传表单流,提取出文件
 * 
 * @param input 上传表单的流
 * @return 是否处理成功
 * @throws IOException IO异常
 */
protected boolean processStream(MultipartRequestInputStream input) throws IOException {
	if (!isAllowedExtension()) {
		// 非允许的扩展名
		log.debug("Forbidden uploaded file [{}]", this.getFileName());
		size = input.skipToBoundary();
		return false;
	}
	size = 0;

	// 处理内存文件
	int memoryThreshold = uploadProperties.memoryThreshold;
	if (memoryThreshold > 0) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(memoryThreshold);
		int written = input.copy(baos, memoryThreshold);
		data = baos.toByteArray();
		if (written <= memoryThreshold) {
			// 文件存放于内存
			size = data.length;
			return true;
		}
	}

	// 处理硬盘文件
	tempFile = FileUtil.createTempFile(TMP_FILE_PREFIX, TMP_FILE_SUFFIX, FileUtil.touch(uploadProperties.tmpUploadPath), false);
	BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
	if (data != null) {
		size = data.length;
		out.write(data);
		data = null; // not needed anymore
	}
	int maxFileSize = uploadProperties.maxFileSize;
	try {
		if (maxFileSize == -1) {
			size += input.copy(out);
			return true;
		}
		size += input.copy(out, maxFileSize - size + 1); // one more byte to detect larger files
		if (size > maxFileSize) {
			// 超出上传大小限制
			tempFile.delete();
			tempFile = null;
			log.debug("Upload file [{}] too big, file size > [{}]", this.getFileName(), maxFileSize);
			input.skipToBoundary();
			return false;
		}
	} finally {
		IoUtil.close(out);
	}
	// if (getFileName().length() == 0 && size == 0) {
	// size = -1;
	// }
	return true;
}