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

标签 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("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?

请注意,文件下载并写入正确,但同样,不在正确的目录中。

最佳答案

替换

new FileOutputStream(file.getName()));

new FileOutputStream(file);

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

关于java - Java 相对路径文件创建中的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13613646/

相关文章:

java - 三星 10 plus 不允许 wifi p2p 发现

java - 我如何在java中管理多个文件和文件夹?

java - 什么代码能够读取program.jar应用程序文件中包含的图像;从任何地方?

java - JPanel里面的另一个

java - 使用 struts 2 表单标签编辑对象的 ArrayList

file - 如何使用 CMake 将多个文件列表合并在一起?

file - 复制包含在不同父文件夹中的许多文件(同名)

java备份mysqldump.exe绝对路径改为相对路径

c# - 将物理路径转换为关于 http ://localhost: 的相对路径

java - 错误java代码eclipse SQL错误: 972, SQLState: 42000 ORA-00972: 标识符太长