org.apache.commons.fileupload.disk.DiskFileItem是否正确创建? [英] org.apache.commons.fileupload.disk.DiskFileItem is not created properly?
问题描述
我正在尝试使用以下示例中显示的代码:
I am trying to use the code shown in the following example:
java.lang.NullPointerException
我的测试方法包含以下代码:
My Test method contains the following code:
final File TEST_FILE = new File("C:/my_text.txt");
final DiskFileItem diskFileItem = new DiskFileItem("fileData", "text/plain", true, TEST_FILE.getName(), 100000000, TEST_FILE.getParentFile());
diskFileItem.getOutputStream();
System.out.println("diskFileItem.getString() = " + diskFileItem.getString());
该位置存在文本文件,但以上代码中的最后一行不输出文件内容.
The text file exists in this location but the last line in the above code does not output the file content.
知道为什么吗?
N.B.
以下内容会打印文件内容:
The following does print the file content:
BufferedReader input = new BufferedReader(new FileReader(TEST_FILE));
String line = null;
while (( line = input.readLine()) != null){
System.out.println(line);
}
推荐答案
在您的第一个代码片段中,您使用OutputStream,但它不起作用.在第二部分中,您将使用InputStream(或它的任何暗示),它会起作用:)您可能想尝试使用getInputStream()代替... OutputStream将写入未读取的字节.
In your first code snip you use an OutputStream and it doesn't work. In the second part you use an InputStream (or whatever impl of this) and it works :) You might want to try with getInputStream() instead... OutputStream is to write bytes not reading.
http://commons.apache.org/fileupload/apidocs /org/apache/commons/fileupload/disk/DiskFileItem.html
尝试这个,很简单,从头开始只是为了提供帮助:
try this one, it's simple and from scratch just to help :
final File TEST_FILE = new File("D:/my_text.txt");
//final DiskFileItem diskFileItem = new DiskFileItem("fileData", "text/plain", true, TEST_FILE.getName(), 100000000, TEST_FILE);
try
{
DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("fileData", "text/plain", true, TEST_FILE.getName());
InputStream input = new FileInputStream(TEST_FILE);
OutputStream os = fileItem.getOutputStream();
int ret = input.read();
while ( ret != -1 )
{
os.write(ret);
ret = input.read();
}
os.flush();
System.out.println("diskFileItem.getString() = " + fileItem.getString());
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
这篇关于org.apache.commons.fileupload.disk.DiskFileItem是否正确创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!