Bennie
Bennie

Reputation: 135

How do I return a file at a specific location in Java?

I am currently using an external library function that returns a File object. This works fine for making the file at a default location, but to accommodate concurrent users, I need to have the file be in a specific folder. Without being able to alter the function that makes the file, is there a File function that let's me specify where it will go to?

Upvotes: 2

Views: 269

Answers (6)

Chris Aldrich
Chris Aldrich

Reputation: 1932

I believe you would have to create a new File object at the location you want and then use FileInputStream to read in your original File and FileOutputStream to write to the location you want.

And if I remember correctly, File.renameTo doesn't always work the best (see Javadoc).

Upvotes: 1

theglauber
theglauber

Reputation: 29665

The java.io.File object is simply an abstract representation of a file or directory pathname, i.e., it's just the file's name and location, not the actual file. Not knowing that library you're using, i don't know if it already created the file, and is simply telling you where it is (i think this is likely), or if it's telling you where to create the file. But it's likely that the answer you're looking for doesn't involve manipulating this File object, but doing something differently with the library to determine where the file will go.

Upvotes: 0

Hunter McMillen
Hunter McMillen

Reputation: 61540

You can use the renameTo(File destination) in the File API to rename the file storing it in another abstract path.

ex:

import java.io.File;

public class MainClass {

  public static void main(String args[]) {

    try {

      File oldFile = new File("/usr/bin/temp/");

      File newFile = new File("/usr/bin/hunter/temp");

      boolean result = oldFile.renameTo(newFile);

      System.out.println(result);
    } 
    catch (Exception e) 
    {
      e.printStackTrace();
    }

Also note that the API says that this is not always guaranteed to succeed, so you need to check the return value of the method call every time you use this method.

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160301

No, you'd need to do something to alter where it creates the file, move the returned file, set a working directory, etc. The latter two could still present issues, though, depending on how the app is set up.

If you have some insight into the method you could use AOP.

Upvotes: 0

chance
chance

Reputation: 6507

First get that file, then move it to your specified location using File.renameTo().

Upvotes: 1

Viruzzo
Viruzzo

Reputation: 3025

You could change the working directory, if only Java let you do that. As it is, if you receive an already created file you can still move it using File.renameTo().

Upvotes: 0

Related Questions