Reading path from ini file, backslash escape character disappearing?

a 夏天 提交于 2019-12-07 06:44:57

问题


I'm reading in an absolute pathname from an ini file and storing the pathname as a String value in my program. However, when I do this, the value that gets stored somehow seems to be losing the backslash so that the path just comes out one big jumbled mess? For example, the ini file would have key, value of:

key=C:\folder\folder2\filename.extension

and the value that gets stored is coming out as C:folderfolder2filename.extension.

Would anyone know how to escape the keys before it gets read in?

Let's also assume that changing the values of the ini file is not an alternative because it's not a file that I create.


回答1:


Try setting the escape property to false in Ini4j.

  • http://ini4j.sourceforge.net/apidocs/org/ini4j/Config.html#setEscape%28boolean%29

You can try:

Config.getGlobal().setEscape(false);



回答2:


If you read the file and then translate the \ to a / before processing, that would work. So the library you are using has a method Ini#load(InputStream) that takes the INI file contents, call it like this:

byte[] data = Files.readAllBytes(Paths.get("directory", "file.ini");
String contents = new String(data).replaceAll("\\\\", "/");
InputStream stream = new ByteArrayInputStream(contents.getBytes());
ini.load(stream);

The processor must be doing the interpretation of the back-slashes, so this will give it data with forward-slashes instead. Or, you could escape the back-slashes before processing, like this:

String contents = new String(data).replaceAll("\\\\", "\\\\\\\\");


来源:https://stackoverflow.com/questions/25001453/reading-path-from-ini-file-backslash-escape-character-disappearing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!