org.apache.commons.fileupload.disk.DiskFileItem is not created properly?

无人久伴 提交于 2019-12-23 18:23:05

问题


I am trying to use the code shown in the following example:

java.lang.NullPointerException while creating DiskFileItem

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.

Any idea why?

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);
}

回答1:


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();
    }



回答2:


A condensed solution with apache IOUtils :

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());

InputStream input =  new FileInputStream(TEST_FILE);
OutputStream os = diskFileItem.getOutputStream();
IOUtils.copy(input, os);

System.out.println("diskFileItem.getString() = " + diskFileItem.getString());


来源:https://stackoverflow.com/questions/8978290/org-apache-commons-fileupload-disk-diskfileitem-is-not-created-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!