简体   繁体   English

如何在要加载的属性文件中指定路径 Java Properties

[英]How to specify a path in a properties file to be loaded with Java Properties

I have a.properties file I want to load in a Java Properties object. The file contains some paths.我有一个 .properties 文件,我想在 Java Properties object 中加载。该文件包含一些路径。 In order to be able to load the properties file without getting a java.lang.IllegalArgumentException: Malformed \uxxxx encoding.为了能够在不获取java.lang.IllegalArgumentException: Malformed \uxxxx encoding. when loading the properties from the file with the method Properties.load(), I need to use the escape character '\' in the path.使用 Properties.load() 方法从文件加载属性时,我需要在路径中使用转义符“\”。

So my path looks like: C:\\Users\\Harald\\Folder1\\Version1\\Folder2 .所以我的路径看起来像: C:\\Users\\Harald\\Folder1\\Version1\\Folder2 And it works this way, no exception is thrown.它以这种方式工作,不会抛出异常。

The problem is that I can't explain to my user (because this path can be changed by the user.) that he needs to use double '\' in the path.问题是我无法向我的用户解释(因为用户可以更改此路径。)他需要在路径中使用双“\”。

Does anybody knows a work-around for this problem?有人知道这个问题的解决方法吗? Thanks!谢谢!

Even simpler solution is to use forward slashes . 更简单的解决方案是使用正斜杠 This way your path will look like C:/Users/Harald/Folder1/Version1/Folder2 and everything else will just work - no code change required! 这样你的路径将看起来像C:/Users/Harald/Folder1/Version1/Folder2 ,其他一切都将正常工作 - 无需更改代码!

I am a bit confused with your question. 我对你的问题有点困惑。 Are you asking if there is a way that you can have a user edit the properties file without having to use non-intuitive \\ escape character? 您是否询问是否有一种方法可以让用户编辑属性文件而无需使用非直观\\转义字符?

If you are setting this up for a user to be able to edit perhaps you should have a program or script to create the properties file (adding in escape characters when needed) 如果您要为用户设置此功能,或许您应该有一个程序或脚本来创建属性文件(在需要时添加转义字符)

You might be better off defining a path for the user to place a properties file, or point them to an existing properties file (that contains comments about useful properties etc.) eg ${user.home}\\\\myapp\\\\myprops.properties and then always load that file, or better yet, just provide the directory and load every file that ends in .properties in that directory. 您可能最好为用户定义路径以放置属性文件,或者将它们指向现有属性文件(包含有用属性的注释等),例如${user.home}\\\\myapp\\\\myprops.properties然后总是加载该文件,或者更好的是,只需提供目录并加载以该目录中的.properties结尾的每个文件。

If your application is a GUI app, you could also allow the user to select a file in a file dialog box. 如果您的应用程序是GUI应用程序,您还可以允许用户在文件对话框中选择文件。 The strings you get back out of swing and SWT labels and file choosers are java friendly and you needn't worry about escape characters. 你从摇摆和SWT标签和文件选择器中获得的字符串是java友好的,你不必担心转义字符。

if in java code use \\如果在 java 代码中使用\\

if in the properties file use /如果在属性文件中使用/

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

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