Question

I referred to this example and created a servlet application.

It works perfectly fine with the TMP_DIR & DEST_DIR paths that is mentioned in the code(I have created a folder named tmp in C drive & also i have created a folder named files inside my application folder.

Now I am shifting the code to a linux machine, where this does not work since there is not drive named C: there. I tried replacing the c:\\tmp of the code to /tmp(and created a folder tmp) inside my application folder. But its not working. How can I make this code generic? Please advise.

Was it helpful?

Solution

If what you want is a temporary directory use http://commons.apache.org/io/apidocs/org/apache/commons/io/FileUtils.html and look for getTempDirectory(). This should work anywhere

So you need the System Temporary directory which is provided by the system. You can get this either through its path or through the actual File. (IOUtils provides both approaches). Here;s the IOUtil docs: getTempDirectory

public static File getTempDirectory()

    Returns a File representing the system temporary directory.

    Returns:
        the system temporary directory.

So if you write:

File myTempFile = IOUtils.getTempDirectory();

then myTempFile will be where you want to write to.

If some app is asking for the directory by name then you can use getTempDirectoryPath() which will give the pathname.

In your example I would write:

private static final String TMP_DIR_PATH = IOUtils.getTempDirectoryPath();

or using @dogbane's approach:

private static final String TMP_DIR_PATH = System.getProperty("java.io.tmpdir");

I'd expect them to give the same answer.

If you are still confused keep asking - that's what SO is for!

UPDATE: If you are doing anything with Files it's worth becoming familiar with Apache's FileUtils and IOUtils. There are several things that the JDK doesn't do well or naturally and Apache gives better support.

OTHER TIPS

The location of the platform-specific directory used to hold temporary files is defined by the property java.io.tmpdir.

So in your code you can use:

private static final String TMP_DIR_PATH = System.getProperty("java.io.tmpdir")

Use File.pathSeparator to get system-dependent path separator.

Edited:

If you just want a temporary dir then use File.createTempFile(..)

Example file path: http://www.exampledepot.com/egs/java.io/ConstructFilePath.html

Example temporary file: http://www.exampledepot.com/egs/java.io/CreateTempFile.html

Edited:

Saving file in Servlet environment: here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top