How to make File Reading Platform Independent in Java

点点圈 提交于 2019-12-08 13:27:24

问题


Hi I am using Maven for Selenium automation tests using Java. I am using Excel Sheet to read data for filling up a registration form. Now It is a normal Maven archetype.

src
--main
  --java
    --mypackage for coding goes here.
  --resources
    --data
      -- the excel sheet
--test
  -- some stuff here under java

currently if I want to read a file I am writing src/main/resources/data/theexcelsheet.xlsx but when I share this jar, I think this will break and I don't want this to break if I package this jar.

How do I make it platform or format independent.

I am using APACHE POI Api if you are thinking how I am reading files.

Someone reading gave me idea that I might be able to use MANIFEST files to do this but I am not sure, can someone help?


回答1:


If you use getResource() to point to your file, the syntax of the path always uses / to separate the components, never \ so you do not have to worry.

In general, outside of a jar, for example if you want to save application settings in a folder, you have to use a OS specific separator - you can obtain it this way:

System.out.println("my" + File.separator + "dir");

Returns my\dir on Win and my/dir on Linux

Of course, that's not enough as you cannot use hardcoded paths like the "c:" drive, but you can get the most common paths reading the System class properties, eg:

System.out.println(System.getProperty("user.home"));

returns C:\Users\piero in Windows7 and /home/piero in Linux



来源:https://stackoverflow.com/questions/13316653/how-to-make-file-reading-platform-independent-in-java

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