How to read file on Windows and Linux from Java

☆樱花仙子☆ 提交于 2019-12-01 14:55:43

If you know the current working directory (test it with:

System.out.println(new File(".").getAbsolutePath());

you can hardcode a relative directory like ../../XML/RequestXML

For the record: although this may help, I still believe you should try to solve this with a configuration parameter or by loading it as a resource available in the classpath.

I don't want two paths

ok then put your the file in the resources folder of your application and try reading it this way

private String filePath  = className.getClass()
                                    .getResource("yourFileName").getPath();
BufferedReader reader = new BufferedReader(new FileReader(filePath));

First a bit of bad news: FileReader is a utility class that as default uses the platform encoding: non-portable. As the encoding is defined in the XML source itself, you might keep to InputStream if possible.

You could keep the XML as read-only resource inside the war/ear.

Or as read-only resource in the jboss directories, outside the application. Using as java resource via the system ClassLoader of jboss.

Or as file, where the path is configured as above. Maybe in an existing properties/xml configuration file. You could also use the jboss admin console to configure a path.

Maybe of interest:

System.getProperty("file.encoding"); // The default encoding
System.getProperty("user.name"); // Under which user are we running
System.getProperty("user.home"); // The user's home
System.getProperty("user.dir"); // The applications working dir

JBoss also defines a couple of things; but that would be non-portable.

Hardcoding file paths is not a recommended practice. You may find a way to build the file path programmatically and use File.separator, which returns the correct one depending on the system ("\" for Windows, and "/" for UNIX/Linux/Macintosh).

DavisTasar

The issue isn't easy to solve because of the fundamental differences in the file systems. (Edit: Ignore me, I'm clearly on Cough Medicine. As Djon pointed out below).

Windows\Uses\Folder\Structures\Like\This.txt

Linux/Uses/Folder/Structures/Like/This.txt

So, the only way to handle this accordingly is to detect the operating system it runs on first, and then build your file paths accordingly.

See this question for more details:

How do I programmatically determine operating system in Java?

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