首页 > 解决方案 > New file in linux environment with absolute path

问题描述

This is the problem:

  1. Path to the folder we want to analyse is correctly retrieved.
  2. We create the file for that folder(with the suposely AbsolutePath). Printing the AbsolutePath now adds a prefix to the original path.
  3. What's in getPath is what should be in getAbsolutePath.
  4. What's being added to the path is the directory where the JVM was run... The absolute path we provided is being wrongly interpreted as a relative path.
  5. We can't detect the files in Ep because the file path doesn't exist.

I've tried creating using Paths.get(string), Paths.get(URI), Paths.get(".").relativize(Path other), etc. Always with the same result.

logger.info("referencePattern.getLocation().getYearFolder(year): "
    + referencePattern.getLocation().getYearFolder(year)); 

File rootFolder = new File(referencePattern.getLocation().getYearFolder(year));
logger.info("rootFolder.getAbsolutePath(): " + rootFolder.getAbsolutePath());

logger.info("rootFolder.getPath(): " + rootFolder.getPath());

logger.info("System.getProperty(\"user.dir\"): " +     System.getProperty("user.dir"));

File[] files = rootFolder.listFiles(filter);

Output:

referencePattern.getLocation().getYearFolder(year): /dvl/app/srs/tomcat/data/dg/ep/docs_autres/commeenne/com/2018/
rootFolder.getAbsolutePath(): /dvl/app/srs/tomcat/temp//dvl/app/srs/tomcat/data/dg/ep/docs_autres/commeenne/com/2018
rootFolder.getPath(): /dvl/app/srs/tomcat/data/dg/ep/docs_autres/commeenne/com/2018
System.getProperty("user.dir"): /dvl/app/srs/tomcat/temp

标签: javalinuxfilepathabsolute

解决方案


来自评论

getYearFolder(year)将以下内容写入日志:

/dvl/app/srs/tomcat/data/ep/docs_autres/commeenne/com/2018/

getYearFolder(year).getBytes("UTF-8")写道:

[36, 123, 115, 121, 115, 58, 117, 115, 101, 114, 46, 104, 111, 109, 101, 125, 47, 100, 97, 116, 97, 47, ...]

显示的字节代表字符串:

${sys:user.home}/data/

似乎logger.info(...)正在做替换,${sys:user.home}/dvl/app/srs/tomcat 记录的输出中替换为。

在 Java 代码中看到的实际值是${sys:user.home}/data/ep/docs_autres/commeenne/com/2018/,它不以 a 开头,/因此被认为是相对路径,因此getAbsolutePath()在当前目录 ( /dvl/app/srs/tomcat/temp) 前加上前缀,结果是:

/dvl/app/srs/tomcat/temp/${sys:user.home}/data/ep/docs_autres/commeenne/com/2018/

然后记录器执行替换为:

/dvl/app/srs/tomcat/temp//dvl/app/srs/tomcat/data/ep/docs_autres/commeenne/com/2018/

需要考虑的事项:

  • 如果getYearFolder(year)应该返回文件路径,为什么要返回${sys:user.home}

  • 在什么时候(代码中的什么地方)${sys:user.home}应该被替换?它肯定需要在被调用之前。 getAbsolutePath()

  • getAbsolutePath()如果返回的路径getYearFolder(year)已经应该是绝对的,为什么会调用它?

这些问题的答案应该为如何解决问题提供指导。


推荐阅读