SoFunction
Updated on 2025-04-14

How to convert inputStream object to File object in java (no local file generated)

Requirement description

Generate Excel file streams through POI in the backend. After converting the output stream (outputStream) to an input stream (inputStream), you need to convert the input stream (inputStream) into a File object.

Problem: If you need to convert the input stream (inputStream) into a File object, you must generate a File object according to the local path, which means that no matter what, you must generate a file locally.

Problem solving

After a series of data inquiries, I found that the following method can roughly meet the needs

import ;
import ;
import ;
import ;
import ;
public class StreamUtil {
    static final String PREFIX = "stream2file";//The prefix string defines the file name; it must be at least three characters    static final String SUFFIX = ".tmp";//The suffix string defines the extension of the file; if null, the suffix ".tmp" will be used    public static File stream2file (InputStream in) throws IOException {
        final File tempFile = (PREFIX, SUFFIX);
        ();
        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            (in, out);
        }
        return tempFile;
    }
}

After we run the above programtempFileThat is the File object we need.

After seeing this, you may be curious, isn’t this a file also generated locally?

However, the file location it generates is stored in the following (in the computer's temporary file directory), so it can be regarded as not being generated locally:

C:\Users\TP\AppData\Local\Temp\

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.