Jiman
Jiman

Reputation: 185

Strange Behavior in Java Relative Path File Creation

I'm having some issues creating a file within a folder in the cwd - I've recently switched from windows to mac, and it appears as though there are some subtle differences in how files are to be created.

    String servername = "123";
    URL url = null;
    URLConnection con = null;
    int i;
    try {
            File parentFolder = new File("test2");
            System.out.println("folder.exists():"+folder.exists()); // true
            System.out.println("folder.isDirectory():"+folder.isDirectory()); // true

            url = new URL("http://"+servername+".foo.com:8080/foo.bar");
            con = url.openConnection();
            File file = new File(parentFolder, servername+"the_file.out");

            file.getParentFile().mkdirs();

            BufferedInputStream bis = new BufferedInputStream(
                            con.getInputStream());
            BufferedOutputStream bos = new BufferedOutputStream(
                            new FileOutputStream(file.getName()));
            while ((i = bis.read()) != -1) {
                    bos.write(i);
            }
            bos.flush();
            bis.close();
    } catch (MalformedInputException malformedInputException) {
            malformedInputException.printStackTrace();
    } catch (IOException ioException) {
            ioException.printStackTrace();
    }

In this code snippet, I'm downloading a file from some webpage and trying to save it in a folder called 'test2' which is in my project root.

The result:

MyProject
  test2
  src
  build
  nbproject
  123the_file.out // why doesn't it go into test2?

As a note, the file downloads and writes correctly, but again, not in the right dir.

Upvotes: 0

Views: 295

Answers (2)

Raffaele
Raffaele

Reputation: 20885

See the Javadoc for File.getName()

Returns the name of the file or directory denoted by this abstract pathname. This is just the last name in the pathname's name sequence. If the pathname's name sequence is empty, then the empty string is returned.

If you pass a String to the FileOutputStream constructor, it tries to figure out what the name represents, and it chooses a file named foo in the current directory. If you want to carry all the information contanined in the File object (included the parent directory test2), just pass the object itself.

Upvotes: 1

Guido Simone
Guido Simone

Reputation: 7952

Replace

new FileOutputStream(file.getName()));

with

new FileOutputStream(file);

Your file object contains both the folder and name of the file. You need to pass the entire file object to FileOutputStream. The way you have it coded you are only passing the name string 123the_file.out so FileOutputStream interprets it as relative to your cwd

Upvotes: 3

Related Questions