Java相对路径文件创建中的奇怪行为

Java相对路径文件创建中的奇怪行为,java,file,relative-path,Java,File,Relative Path,我在cwd中的文件夹中创建文件时遇到了一些问题-我最近从windows切换到mac,似乎在创建文件的方式上存在一些细微的差异 String servername = "123"; URL url = null; URLConnection con = null; int i; try { File parentFolder = new File("test2"); System.out.println("fo

我在cwd中的文件夹中创建文件时遇到了一些问题-我最近从windows切换到mac,似乎在创建文件的方式上存在一些细微的差异

    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();
    }
在这段代码片段中,我从某个网页下载了一个文件,并试图将其保存在名为“test2”的文件夹中,该文件夹位于我的项目根目录中

结果是:

MyProject
  test2
  src
  build
  nbproject
  123the_file.out // why doesn't it go into test2?
需要注意的是,文件下载和写入正确,但仍然不是在正确的目录中。

Replace

new FileOutputStream(file.getName()));

文件
对象包含文件夹和文件名。您需要将整个文件对象传递给FileOutputStream。按照编码方式,您只需将名称字符串
123传递给_file.out
,因此FileOutputStream将其解释为相对于您的cwd

替换

new FileOutputStream(file.getName()));

文件
对象包含文件夹和文件名。您需要将整个文件对象传递给FileOutputStream。按照编码方式,您只需将名称字符串
123传递给_文件.out
,因此FileOutputStream将其解释为相对于您的cwd

有关详细信息,请参阅Javadoc

返回此摘要表示的文件或目录的名称 路径名。这只是路径名名称序列中的姓氏。 如果路径名的名称序列为空,则空字符串为空 返回

如果将
字符串
传递给构造函数,它将尝试找出名称代表的内容,并在当前目录中选择名为
foo
的文件。如果您想携带
文件
对象中包含的所有信息(包括父目录
test2
),只需传递对象本身即可

有关详细信息,请参阅Javadoc

返回此摘要表示的文件或目录的名称 路径名。这只是路径名名称序列中的姓氏。 如果路径名的名称序列为空,则空字符串为空 返回

如果将
字符串
传递给构造函数,它将尝试找出名称代表的内容,并在当前目录中选择名为
foo
的文件。如果您想携带
文件
对象中包含的所有信息(包括父目录
test2
),只需传递对象本身即可