Java 9新增的一个方法InputStream.transferTo()

本文介绍Java9如何通过新增的InputStream.transferTo方法简化了网络请求的处理过程,演示了一个类似curl命令的Java程序,该程序可以轻松打印出指定URL的内容。

在Java每个重要的发型版本中,都会有许多新的特性被加入到类库中,所以与这些新特性保持同步是值得的。

假设想要编写一个程序,用它打印出命令行中指定的一条URL的实际内容(类似于curl命令)。在Java 9之前,这些代码有点烦琐,但是Java 9在InputStream中增加了transferTo方法,程序一下子就简单了很多:

public class Curl {
    public static void main(String[] args) throws IOException {
        try (InputStream in = new URL(args[0]).openStream()) {
            in.transferTo(System.out);
        }
    }
}

 

package com.itheima.controller; import com.itheima.common.ApiResponse; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.*; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.nio.channels.FileChannel; import java.nio.file.*; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; @Controller public class TextToAudioStreamController { @Value("${upload.directory:C:\\Users\\htxu12\\Desktop\\audio}") private String uploadDirectory; private static final String AUDIO_FILE_PATH = "C:\\Users\\htxu12\\Desktop\\wav\\16k1.wav"; // 替换为你的音频文件路径 private static final int BUFFER_SIZE = 1280; // 任务状态类 private final Map<String, Boolean> audioGenerationStatus = new ConcurrentHashMap<>(); private final Map<String, Path> audioFilePaths = new ConcurrentHashMap<>(); private final Map<String, String> uploadedAudioFiles = new ConcurrentHashMap<>(); @GetMapping("/playAudio") public String playAudio() { return "playAudio"; // 返回模板名称,不带扩展名 } @PostMapping(path = "/process-audio-text", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<?> processAudioText( @RequestParam("text") String text, @RequestParam("taskId") String taskId, @RequestParam("audioId") String audioId) throws IOException { System.out.println("收到的文本内容: " + text); System.out.println("使用的音频ID: " + audioId); Path audioPath = Paths.get(uploadDirectory, audioId); if (!Files.exists(audioPath)) { return ResponseEntity.badRequest().body("音频文件不存在"); } audioGenerationStatus.put(taskId, false); new Thread(() -> { try { System.out.println("开始生成音频:" + text); // 模拟长时间音频生成过程(如调用 TTS) Thread.sleep(15000); // 假设生成耗时 5 秒 // 生成完成后保存路径 Path path = Paths.get("C:\\Users\\htxu12\\Desktop\\wav\\16k.wav"); // 假设已生成文件并保存到 path audioFilePaths.put(taskId, path); audioGenerationStatus.put(taskId, true); } catch (Exception e) { e.printStackTrace(); audioGenerationStatus.put(taskId, true); // 标记为完成,但失败 } }).start(); return ResponseEntity.ok(taskId); } @GetMapping("/check-status") @ResponseBody public Map<String, Object> checkStatus(@RequestParam String taskId) throws IOException { boolean isGenerated = audioGenerationStatus.getOrDefault(taskId, false); boolean exists = audioFilePaths.containsKey(taskId); Map<String, Object> response = new HashMap<>(); response.put("generated", isGenerated); response.put("exists", exists); if (exists) { response.put("audioUrl", "/stream-audio/" + taskId); } if (!isGenerated) { response.put("status", "processing"); } else if (isGenerated) { if (Files.exists(audioFilePaths.get(taskId))) { response.put("status", "completed"); } else { response.put("status", "error"); } } return response; } @PostMapping("/cancel-task") public ResponseEntity<?> cancelTask(@RequestParam String taskId) { audioFilePaths.remove(taskId); return ResponseEntity.ok("任务已取消"); } @GetMapping("/stream-audio") public void streamAudio(@RequestParam String taskId, HttpServletResponse response) throws IOException { Path path = audioFilePaths.get(taskId); if (path == null || !Files.exists(path)) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "音频未生成"); return; } response.setContentType("audio/wav"); response.setHeader("Content-Disposition", "inline"); response.setHeader("Cache-Control", "no-cache"); try (InputStream inputStream = new BufferedInputStream(new FileInputStream(path.toFile())); OutputStream outputStream = response.getOutputStream()) { byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } } } @PostMapping("/upload-audio") public ResponseEntity<?> uploadAudio(@RequestParam("file") MultipartFile file) throws IOException { Path uploadPath = Paths.get(uploadDirectory); if (!Files.exists(uploadPath)) { Files.createDirectories(uploadPath); } String originalFilename = StringUtils.cleanPath(file.getOriginalFilename()); String fileExtension = ""; String baseName = originalFilename; int dotIndex = originalFilename.lastIndexOf("."); if (dotIndex > 0) { fileExtension = originalFilename.substring(dotIndex).toLowerCase(); baseName = originalFilename.substring(0, dotIndex); } if (!fileExtension.equals(".wav")) { return ResponseEntity.badRequest().body("只允许上传 .wav 文件"); } String newFilename = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + "_" + baseName + ".wav"; Path filePath = uploadPath.resolve(newFilename); file.transferTo(filePath); uploadedAudioFiles.put(newFilename, newFilename); Map<String, Object> response = new HashMap<>(); response.put("filename", newFilename); return ResponseEntity.ok(ApiResponse.ok("文件上传成功",response)); } } 修改为 /process-audio-text接口逻辑 得等上一个请求处理完异步 才处理下一个请求
最新发布
08-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值