2

i am using a java code that in the middle of the code it will excute a text file of a directory to read it again late. in windows this text file get saved in C drive

is there a code which look up the drive path and use it so i can make the app compatible with Mac os and any other OS Instead of creating 3 different types of codes and 3 different programs.

thank you

Zyzz Shembesh
  • 220
  • 3
  • 19
  • Better define path in properties file and read it from them so it could be different in different environment and different directory not necessary you need to replicate from windows to linux and vice versa. – SMA Jan 01 '15 at 16:05
  • Can you explain who will write this text file? If just a read-only file, you can place it into resources folder (folder defined by maven) and read it as a resource stream. If a temp file, you had better put it into **temp folder**. See http://stackoverflow.com/questions/617414/create-a-temporary-directory-in-java – auntyellow Jan 01 '15 at 16:23

1 Answers1

4

One way of making the paths platform agnostic is to use the user home folder and work with created files/folders relative to it.

To get the path of user in Java, you can use System.getProperty("user.home").

Let's say you want to then use this path and create a new file under it. This can be done as follows:

String userHomePath = System.getProperty("user.home");
File myFile = new File(userHomePath + "/someFolder/someFile.txt");
// Do whatever we want with this file

Note that / for file separator will work on all platforms. You can also use File.separator instead.

Invisible Arrow
  • 4,625
  • 2
  • 23
  • 31
  • Good answer! experience suggests to never use File.separator except when absolutely necessary, as it causes innumerable portability (and other) problems. It's generally only needed when passing a path to a program or user interface that requires or expects it. For example, calling cmd.exe /c requires backslashes. – philwalk Feb 02 '18 at 20:15