需要根據可用資料創建一個txt檔案,然后需要將該檔案作為rest回應發送。該應用程式部署在容器中。我不想將它存盤在容器上的任何位置或 Spring Boot 資源中的任何位置。有什么方法可以讓我們在運行時緩沖區創建檔案而不提供任何檔案位置,然后在休息回應中發送它?應用程式是生產應用程式,所以我需要一個安全的解決方案
uj5u.com熱心網友回復:
一個檔案就是一個檔案。您使用了錯誤的詞 - 在 Java 中,資料流的概念,至少對于此類作業,稱為 anInputStream或 an OutputStream。
無論你有什么方法需要一個File? 那是路的盡頭。一個檔案就是一個檔案。你不能偽造它。但是,與開發人員交談,或檢查替代方法,因為在 java 中進行資料處理的任何內容都絕對沒有理由需要File. 它應該需要一個InputStream或可能是一個Reader. 或者甚至有一種方法可以為您提供OutputStream或Writer。所有這些都很好——它們是抽象的,讓你可以從檔案、網路連接或整塊布向它發送資料,這就是你想要的。
一旦你擁有其中之一,這就是微不足道的。例如:
String text = "The Text you wanted to store in a fake file";
byte[] data = text.getBytes(StandardCharsets.UTF_8);
ByteArrayInputStream in = new ByteArrayInputStream(data);
whateverSystemYouNeedToSendThisTo.send(in);
或者例如:
String text = "The Text you wanted to store in a fake file";
byte[] data = text.getBytes(StandardCharsets.UTF_8);
try (var out = whateverSystemYouNeedToSendThisTo.getOUtputStream()) {
out.write(data);
}
uj5u.com熱心網友回復:
看看下面的函式:
進口
import com.google.common.io.Files;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import java.io.*;
import java.nio.file.Paths;
功能:
@GetMapping(value = "/getFile", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
private ResponseEntity<byte[]> getFile() throws IOException {
File tempDir = Files.createTempDir();
File file = Paths.get(tempDir.getAbsolutePath(), "fileName.txt").toFile();
String data = "Some data"; //
try (FileWriter fileWriter = new FileWriter(file)) {
fileWriter.append(data).flush();
} catch (Exception ex) {
ex.printStackTrace();
}
byte[] zippedData = toByteArray(new FileInputStream(file));
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentDisposition(ContentDisposition.builder("attachment").filename("file.txt").build());
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
httpHeaders.setContentLength(zippedData.length);
return ResponseEntity.ok().headers(httpHeaders).body(zippedData);
}
public static byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[in.available()];
int len;
// read bytes from the input stream and store them in buffer
while ((len = in.read(buffer)) != -1) {
// write bytes from the buffer into output stream
os.write(buffer, 0, len);
}
return os.toByteArray();
}
uj5u.com熱心網友回復:
簡而言之,您希望將資料存盤在記憶體中。基本構建塊是位元組陣列 - byte[]。在 JDK 中,有兩個類可以將 IO 世界與位元組陣列連接起來 -ByteArrayInputStream和ByteArrayOutputStream.
休息與處理檔案時一樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/393808.html
下一篇:C#檔案輸出列印超過1次
