Java流形式返回前端的實現(xiàn)示例
前言
為了實現(xiàn)像ChatGPT一樣的效果:文字進行逐個顯示,后端返回的時候需要以流的形式。
一、字符串流
@PostMapping("returnStream")
public void returnStream(HttpServletResponse response) throws IOException {
String message = "我是一段等待已流形式返回的文字";
// 以流的形式返回
ServletOutputStream out = null;
ByteArrayOutputStream baos = null;
try {
InputStream inStream = new ByteArrayInputStream(message.getBytes());
byte[] buffer = new byte[1024];
int len;
baos = new ByteArrayOutputStream();
while ((len = inStream.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
out = response.getOutputStream();
out.write(baos.toByteArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
Objects.requireNonNull(baos).flush();
baos.close();
Objects.requireNonNull(out).flush();
out.close();
}
}
二、文件流
ServletOutputStream out = null;
ByteArrayOutputStream baos = null;
try {
File file=new File(filename);
InputStream inStream=new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
baos = new ByteArrayOutputStream();
while ((len = inStream.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
out = response.getOutputStream();
out.write(baos.toByteArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
baos.flush();
baos.close();
out.flush();
out.close();
}到此這篇關(guān)于Java流形式返回前端的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)Java流形式返回前端內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java并發(fā)編程Callable與Future的應(yīng)用實例代碼
這篇文章主要介紹了Java并發(fā)編程Callable與Future的應(yīng)用實例代碼,具有一定借鑒價值,需要的朋友可以參考下2018-01-01
解決bootstrap.yml不生效,無法優(yōu)先于application.yml文件加載問題
文章主要討論了在Spring Boot項目中,`bootstrap.yml`文件無法優(yōu)先于`application.yml`文件加載的問題,原因是缺少了`nacos-config`依賴,且需要確保Spring Boot版本與`nacos-config`版本匹配,作者希望通過分享個人經(jīng)驗,幫助他人解決類似問題2024-12-12
SpringBoot?+?layui?框架實現(xiàn)一周免登陸功能示例詳解
這篇文章主要介紹了SpringBoot+layui框架實現(xiàn)一周免登陸功能,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08
如何解決EasyExcel導出文件LocalDateTime報錯問題
這篇文章主要介紹了如何解決EasyExcel導出文件LocalDateTime報錯問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
mybatisplus實現(xiàn)自動創(chuàng)建/更新時間的項目實踐
Mybatis-Plus提供了自動填充功能,可以通過實現(xiàn)MetaObjectHandler接口來實現(xiàn)自動更新時間的功能,本文就來介紹一下mybatisplus實現(xiàn)自動創(chuàng)建/更新時間的項目實踐,感興趣的可以了解下2024-01-01

