开发者

Accessing external files within Java applications under Windows and Linux Operating Systems

Please I am facing the following issue:

Throughout my Java program, i am accessing some fil开发者_Go百科es which it seems they are being accessed in a different way under windows compared to Linux. For example, if i wanted to access the following file within the same folder as the project i would write the following:

Under Linux: File Operations_File = new File("Data/Operations.txt");

Under Windows: File Operations_File = new File("Data\\Operations.txt");

I will be needing a standard methodology that works under all operating systems (or at least those two). As coding two versions of my code is not elegant at all.

My Two operating system that I am operating on are: Linux Mint 9 and Windows XP. I used NetBeans 6.9.1 throughout all the project.

Your help is greatly appreciated!


File.separator is exactly for this.

File f = new File("Data" + File.separator + "Operations.txt");

Don't get confused with File.pathSeparator, that is used to separate paths from each other. For example:

/usr/local/lib:/usr/lib:/var/lib

In the above example, : is the path separator (windows uses ; for path separators).


You can also create a File representing the directory and another File representing something in that directory like this:

File dataDir = new File("Data");
File operationsFile = new File(dataDir, "Operations.txt");

You could also skip the File for the directory and just do this as well:

File operationsFile = new File("Data", "Operations.txt");

Under Windows, printing out operationsFile gives Data\Operations.txt as expected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜