java – org.apache.commons.fileupload.disk.DiskFileItem未正确创建?
作者:互联网
我正在尝试使用以下示例中显示的代码:
java.lang.NullPointerException while creating DiskFileItem
我的Test方法包含以下代码:
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());
文本文件存在于此位置,但上述代码中的最后一行不输出文件内容.
知道为什么吗?
注:
以下是打印文件内容:
BufferedReader input = new BufferedReader(new FileReader(TEST_FILE));
String line = null;
while (( line = input.readLine()) != null){
System.out.println(line);
}
解决方法:
在您的第一个代码片段中,您使用OutputStream并且它不起作用.在第二部分中,您使用一个InputStream(或其中任何impl)并且它可以工作:)您可能想尝试使用getInputStream()而不是… OutputStream是写入不读取的字节.
http://commons.apache.org/fileupload/apidocs/org/apache/commons/fileupload/disk/DiskFileItem.html
尝试这个,它很简单,从头开始只是为了帮助:
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();
}
标签:java,spring,spring-mvc,junit,apache-commons 来源: https://codeday.me/bug/20190726/1540255.html