【问题标题】:How to create file in 'src' (source) directory without specifing the drive如何在不指定驱动器的情况下在“src”(源)目录中创建文件
【发布时间】:2014-10-01 19:29:23
【问题描述】:

我知道如何在 Java 中创建具有特定路径的文件。
我想在项目的源文件夹中创建文件而不指定驱动器,因为它可以从 PC 更改为 PC。

我尝试使用:

File targetFile = new File("/src/SavedGames/uploadedFile.xml");
targetFile.createNewFile();

在 'src' 前加点:

File targetFile = new File("./src/SavedGames/uploadedFile.xml");
targetFile.createNewFile();

\\:

File targetFile = new File("\\src\\SavedGames\\uploadedFile.xml");
targetFile.createNewFile();

它不起作用,它抛出异常。

这个工作,但在我的 Apache 服务器文件夹上创建它:

File targetFile = new File("uploadedFile.xml");
targetFile.createNewFile();

这是层次结构:

代码运行在LoadGameServlet.java

【问题讨论】:

  • 你试过src/SavedGames/uploadedFile.xml吗?
  • 现在检查:它尝试创建在 c:\myApacheServer\bin\src\SavedGames
  • 如果 src/SavedGames/iploadedFile.xml 不起作用,请检查 mainfest.mf 中的 Class-Path 以确保它指向项目的根目录。
  • @SualehFatehi,该解决方案对我不起作用。我尝试了解决方案: URL path = Thread.currentThread().getContextClassLoader().getResource("src/SavedGames/");但它仍然在 apache 服务器上创建它

标签: java jakarta-ee servlets src


【解决方案1】:

您可以使用System.out.println(targetFile.getAbsolutePath()) 之类的东西来调试文件的创建位置,甚至在创建实际文件之前。

【讨论】:

  • 好主意,它在 C:\src\SavedGames 上创建 - 没有这样的目录。
  • 您应该先创建文件夹,或者使用.mkdirs() 函数以编程方式创建它。
  • 但我不想在“C:”驱动器上创建它,因为用户可能已经拥有这样的文件夹。我想在我的服务器 SavedGames 包上创建它。
  • 您在运行时的当前文件夹似乎是 Apache 文件夹,因此“src/”或“./src/”等所有相对路径都相对于该文件夹。您应该确保使用“..”和相关文件夹的正确组合将文件指向您想要的位置。
  • 另外,如果您在文件夹名称中使用“..”,您还可以使用targetFile.getCanonicalPath() 方法来解析文件将存储到的确切位置。
【解决方案2】:

经过大量搜索,我找到了一种方法。

File targetFile = new File(new File(LoadGameServlet.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParent() + "\\uploadedFile.xml");
String decoderPath = java.net.URLDecoder.decode(targetFile.getPath(), "UTF-8");
String newPath = decoderPath .replaceAll("build\\\\web\\\\WEB-INF\\\\classes\\\\Servlets", "src\\\\java\\\\SavedGames");
targetFile = new File(newPath);
targetFile.createNewFile();

我检查了它,它工作正常。

感谢您的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 2011-02-12
    • 2014-07-30
    相关资源
    最近更新 更多