简体   繁体   English

从包含环境变量的路径中检查Java是否存在文件

[英]Check from Java if a file exists, from a path containing environment variables

Is there an existing Java solution to resolve file paths containing environment variables? 是否有现有的Java解决方案来解析包含环境变量的文件路径?

I need to convert this (simplified) method to handle the case where the provided path contains an environment variable (like %PROGRAMFILES(X86)%\\SomeProgram\\SomeFile.ini). 我需要转换此(简化)方法来处理提供的路径包含环境变量的情况(如%PROGRAMFILES(X86)%\\ SomeProgram \\ SomeFile.ini)。

I know how to write code to extract the variable names, fetch their values and substitute them in the provided string but I can't help but feel I'm reinventing the wheel... 我知道如何编写代码来提取变量名,获取它们的值并在提供的字符串中替换它们但我不禁觉得我正在重新发明轮子......

boolean isValidPath(String pathToValidate) {
  File f = new File(pathToValidate);
  if(f.exists()) {
    return true;
  }  
  return false;
}

Almost sure it does not exist in standard library simply because any environment variable is very specific in its usage. 几乎可以肯定它不存在于标准库中,因为任何环境变量的使用都非常具体。 Some allow lists delimited by semicolons like PATH, some - only one single value. 有些允许列表由分号(如PATH)分隔,有些 - 只有一个值。 Also relying on values of env vars means that code becomes more platform-specific, and jre seems to avoid it at any reasonable cost. 同样依赖env vars的值意味着代码变得更加特定于平台,并且jre似乎以任何合理的代价避免它。

There are already a couple of implementations of such substitutors on github, for example https://github.com/Haufe-Lexware/java-env-replacer . 在github上已经有几个这样的替代品的实现,例如https://github.com/Haufe-Lexware/java-env-replacer

You can actually get the environment variables details by calling System.getenv() and then you can write some logic (sample shown below) to achieve what you wanted: 您可以通过调用System.getenv()实际获取环境变量的详细信息,然后您可以编写一些逻辑(下面显示的示例)来实现您想要的:

public boolean isValidPath(String pathToValidate) {
  String envValue = "";
  for (String envName : env.keySet()) {
      if(pathToValidate.contains(envName)) {
             envValue= env.get(envName);
             break;
      }
  }
  //replace the envValue in pathToValidate
  //Then check file exists or not & return true/false
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM