首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Java实现InputStream到FileItem的转换

用Java实现InputStream到FileItem的转换
EN

Stack Overflow用户
提问于 2012-05-10 15:26:31
回答 1查看 19K关注 0票数 0

如何在Java中实现从InputStream到FileItem的转换?

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-05-10 16:06:23

下面是一个有效的示例。请注意,您必须使用InputStream更改示例中的InputStream,并且您可能还希望更改工作/tmp dir()的位置。

代码语言:javascript
复制
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.
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10529270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档