How do I get an FileInputStream from FileItem in java?

6.3k Views Asked by At

I am trying to avoid the FileItem getInputStream(), because it will get the wrong encoding, for that I need a FileInputStream instead. Is there any way to get a FileInputStream without using this method? Or can I transform my fileitem into a file?

if (this.strEncoding != null && !this.strEncoding.isEmpty()) {
    br = new BufferedReader(new InputStreamReader(clsFile.getInputStream(), this.strEncoding));
} 
else {
    // br = ?????
}
3

There are 3 best solutions below

7
On

An InputStream is binary data, bytes. It must be converted to text by giving the encoding of those bytes.

Java uses internally Unicode to represent all text scripts. For text it uses String/char/Reader/Writer.

For binary data, byte[], InputStream, OutputStream.

So you could use a bridging class, like InputStreamReader:

String encoding = "UTF-8"; // Or "Windows-1252" ...
BufferedReader in = new BufferedStream(
    new InputStreamReader(fileItem.getInputStream(),
                          encoding));

Or if you read the bytes:

String s = new String(bytes, encoding);

The encoding is often an option parameter (there then exists an overloaded method without encoding).

2
On

You can use the write method here.

File file = new File("/path/to/file");
fileItem.write(file);
1
On

You can try

FileItem#getString(encoding)

Returns the contents of the file item as a String, using the specified encoding.