2

I am trying to get the following code to work properly. It always prints the output from the catch block, even though the output that is only printed if the file exists, is printed.

String outputFile = "/home/picImg.jpg";
File outFile = new File(outputFile);
if(outFile.exists)
    newStatus(" File does indeed exist");
FileOutputStream fos;
try {
    fos = new FileOutputStream(outFile);
    fos.write(response);
    fos.close();
    return outputFile;
} catch (FileNotFoundException ex) {
    newStatus("Error: Couldn't find local picture!");
    return null;
} 

In the code response is a byte[] containig a .jpg image from a URL. Overall I am trying to download an image from a URL and save it to the local file system and return the path. I think the issue has to do with read/write permissions within /home/. I chose to write the file there because I'm lazy and didn't want to find the username to find the path /home/USER/Documents. I think I need to do this now.

I notice in the terminal I can do cd ~ and get to /home/USER/. Is there a "path shortcut" I can use within the file name so that I can read/write in a folder that has those permissions?

M. A. Kishawy
  • 5,001
  • 11
  • 47
  • 72
KDecker
  • 6,928
  • 8
  • 40
  • 81
  • possible duplicate of [What is the best way to find the users home directory in Java?](http://stackoverflow.com/questions/585534/what-is-the-best-way-to-find-the-users-home-directory-in-java) – Biffen Nov 10 '14 at 21:23
  • Mind that `"/home/picImg.jpg"` probably isn't where you plan to put the file, rather `"/home//picImg.jpg"`. – mattias Nov 10 '14 at 21:35

3 Answers3

4

~ expansion is a function of your shell and means nothing special for the file system. Look for Java System Properties "user.home"

Oncaphillis
  • 1,888
  • 13
  • 15
4

No. The ~ is expanded by the shell. In Java File.exists() is a method, you can use File.separatorChar and you can get a user's home folder with System property "user.home" like

String outputFile = System.getProperty("user.home") + File.separatorChar
                  + "picImg.jpg";
File outFile = new File(outputFile);
if (outFile.exists())

Edit

Also, as @StephenP notes below, you might also use File(File parent, String child) to construct the File

File outFile = new File(System.getProperty("user.home"), "picImg.jpg");
if (outFile.exists())
Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 3
    Using `new File(parent, child)` takes care of the separatorChar for you... e.g. `File outFile = new File(System.getProperty("user.home"), "picImg.jpg");` – Stephen P Nov 10 '14 at 21:55
2

Java provides a System property to get the user home directory: System.getProperty("user.home");. The advantage of this is, that it works for every operating system that can run the Java virtual machine.

More about System properties: Link.

Tom
  • 16,842
  • 17
  • 45
  • 54