gpt4 book ai didi

java - 在 Java 中将 InputStream 转换为 FileItem

转载 作者:行者123 更新时间:2023-12-01 19:04:46 28 4
gpt4 key购买 nike

如何在 Java 中从 InputStream 转换为 FileItem?

谢谢。

最佳答案

这是一个工作示例。请注意,您必须使用 InputStream 更改示例中的 InputStream,并且您可能还需要更改 work/tmp dir() 的位置。

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;


public class TestFile {

public static void main(String args[]) throws IOException {
// This is a sample inputStream, use your own.
InputStream inputStream = new FileInputStream("c:\\Kit\\Apache\\geronimo-tomcat6-javaee5-2.1.6\\README.txt");

int availableBytes = inputStream.available();

// Write the inputStream to a FileItem
File outFile = new File("c:\\tmp\\newfile.xml"); // This is your tmp file, the code stores the file here in order to avoid storing it in memory
FileItem fileItem = new DiskFileItem("fileUpload", "plain/text", false, "sometext.txt", availableBytes, outFile); // You link FileItem to the tmp outFile
OutputStream outputStream = fileItem.getOutputStream(); // Last step is to get FileItem's output stream, and write your inputStream in it. This is the way to write to your FileItem.

int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}

// Don't forget to release all the resources when you're done with them, or you may encounter memory/resource leaks.
inputStream.close();
outputStream.flush(); // This actually causes the bytes to be written.
outputStream.close();

// NOTE: You may also want to delete your outFile if you are done with it and dont want to take space on disk.
}
}

关于java - 在 Java 中将 InputStream 转换为 FileItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10529270/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com