本文介绍了org.apache.commons.fileupload.disk.DiskFileItem 未正确创建?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下示例中显示的代码:

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

java.lang.NullPointerException 在创建 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.

知道为什么吗?

注意

以下确实打印文件内容:

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 未正确创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 15:34