-1
A
回答
4
這是一個工作示例。請注意,您必須使用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.
}
}
相關問題
- 1. Java:將InputStream轉換爲OutputStream
- 2. 在java中將InputStream轉換爲MappedByteBuffer?
- 3. FileItem inputStream到FileInputStream
- 4. java將inputStream轉換爲base64字符串
- 5. 將Jetty Buffer轉換爲InputStream
- 6. 將inputStream轉換爲FileInputStream?
- 7. 將InputStream轉換爲BufferedReader
- 8. 將InputStream轉換爲FileInputStream
- 9. 將InputStream轉換爲MediaPlayer
- 10. 將InputStreamReader轉換爲InputStream
- 11. 如何在Java ME中將StringBuffer轉換爲InputStream?
- 12. 在Java中,如何將InputStream轉換爲字節數組(byte [])?
- 13. 如何在Java/Groovy中將InputStream轉換爲BufferedImage?
- 14. 如何將InputStream轉換爲Java中的字符串?
- 15. 的Java轉換的InputStream URL
- 16. Java - byte [] to FileItem
- 17. 將UTF字符串轉換爲InputStream
- 18. 如何將InputStream轉換爲FileStream?
- 19. 如何將InputStream轉換爲Source?
- 20. 將InputStream轉換爲字符串(telnet)
- 21. 將SAX ContentHandler字符(..)轉換爲InputStream
- 22. 將inputStream從ZipFile轉換爲字符串
- 23. 如何將byte []轉換爲InputStream?
- 24. 如何將對象轉換爲InputStream
- 25. 如何將InputStream轉換爲DataHandler?
- 26. 將InputStream(圖片)轉換爲ByteArrayInputStream
- 27. 如何將javax.xml.transform.Source轉換爲InputStream?
- 28. 如何將JSP InputStream轉換爲ServletResponse?
- 29. 將Java InputStream轉換爲流,而不是Strings
- 30. 如何將InputStream()轉換爲掃描器()Java
FileItem是什麼API? – Vulcan
org.apache.commons.fileupload – MrGreen