Кодировка URL, пробелы и специальные символы (например, «+»).Как правильно управлять путями к файлам? - PullRequest
0 голосов
/ 31 мая 2018

Я читал тонны постов с переполнением стека о кодировках путей Java и правильных способах управления путями файлов.Я читал .Тем не менее, я не могу понять, как правильно управлять моим путем к файлу.

То, чего я хочу достичь, довольно просто: получить путь к файлу * .jar, закодированный надлежащим образом (чтобы без «% 20» и специальных специальных символов, правильно управляемых), чтобы я мог использовать его каквход в FileInputStream (): таким образом, я могу использовать его для загрузки файла свойств, который находится в той же папке вышеупомянутого * .jar.

Я прочитал документацию по Java и понял, что URLDecoderпросто экранирует специальные символы (например, "+") с пробелами, поэтому я не могу точно определить, какую комбинацию методов я должен использовать, чтобы получить абсолютный путь к файлу, даже если его папки (не по моей вине) содержат белый цветпробелы и указанные символы.Это мой метод:

private FileInputStream loadInputPropertiesFile() {
    FileInputStream input = null;

    // Let's load the properties file from the *.jar file parent folder.
    File jarPath = new File(PropertiesManagement.class.getProtectionDomain().getCodeSource().getLocation().getPath());
    String propertiesPath = String.format("%s/", jarPath.getParentFile().getAbsolutePath());

    propertiesPath = URLDecoder.decode(propertiesPath, StandardCharsets.UTF_8);

    // This part has been added just for tests, to better understand how file paths were encoded.
    try {
        URL url = jarPath.toURI().toURL();
        File path = Paths.get(url.toURI()).toFile();
        System.out.println(path);
    } catch (MalformedURLException | URISyntaxException e) {
        e.printStackTrace();
    }

    try {
        input = new FileInputStream(propertiesPath + CONFIG_FILE_PATH);
    } catch (FileNotFoundException e) {
        System.out.println("Properties file not found! Have you deleted it?");
        e.printStackTrace();
    }

    return input;
}

РЕДАКТИРОВАТЬ
Путь к файлу, который я хотел бы получить, выглядит примерно так: "C: \ Some + Folder \ x64 \".
В конце возвращаемый ввод должен выглядеть примерно так: «C: \ Some + Folder \ x64 \ config.properties».

Ответы [ 2 ]

0 голосов
/ 01 июня 2018

В конце концов я исправил это, и он работает и для путей со специальными символами.
Надеюсь, это поможет кому-то, у кого возникла та же проблема.

/**
 * It loads the 'config.properties' file into a FileInputStream object.
 *
 * @return The FileInputStream object.
 */
private FileInputStream loadInputPropertiesFile() {
    FileInputStream input = null;

    // Let's load the properties file from the *.jar file parent folder...
    File jarPath = new File(PropertiesManagement.class.getProtectionDomain().getCodeSource().getLocation().getPath());
    String propertiesPath = String.format("%s" + File.separator, jarPath.getParentFile().getAbsolutePath());
    propertiesPath = propertiesPath.replace("%20", "\u0020");

    try {   
        // ... and setting the pointer to the same path, ready to read the properties file.
        input = new FileInputStream(propertiesPath + CONFIG_FILE_PATH);
    } catch (FileNotFoundException e) {
        System.out.println("Properties file not found! Have you deleted it?");
        e.printStackTrace();
    }

    return input;
}
0 голосов
/ 31 мая 2018

Вы должны просто добавить родительскую папку в путь к классам и загрузить ее как обычно:

//load a properties file from class path, inside static method
Properties prop = new Properties();
try(final InputStream stream = 
   Classname.class.getClassLoader().getResourceAsStream("foo.properties")) {
    prop.load(stream);
}
// or load it within an instance
try(final InputStream stream =
    this.getClass().getResourceAsStream("foo.properties")) {
    prop.load(stream);
}

И вместо "% s /" было бы лучше использовать "% s" +File.separator, который всегда дает вам независимый от платформы разделитель.

...