rkvonline
rkvonline

Reputation: 25

how to create a text file in unix server using a java code?

I'm new in java. I have done an application and it contains a property file in which log path is configured. It is working fine in windows. This is the method for the same.

                  File file = new File(logPath);
                  file.createNewFile();

Actually this tool has developed for a third party and they are running in unix os. My question is, this file creation will work in UNIX platform or needs to change the code for that ?

Upvotes: 0

Views: 5693

Answers (2)

Jamie Cockburn
Jamie Cockburn

Reputation: 7555

Yes and no.

If logpath is an absolute path, then no. In Windows, this would contain a drive letter and such a path would not be understood by a *nix OS. This For example would not work:

"C:\log.txt"

If it is not an absolute path, but a relative one, then it should just work as the other answers state. For example, this will work:

"data\log.txt"

Such a file would be saved relative to the running programs working directory, so if you were running this (on *nix) from /home/user/, then the file would be created at /home/user/data/log.txt (assuming the data folder already existed).

Obviously, this file then moves around depending on where you were when you started the program.

The best solution is to save this data to the user's home directory, which is a common concept on all the platforms you've mentioned:

String home = System.getProperty("user.home");

File data_directory = new File(home, ".my_app_data");
data_directory.mkdir();

File log_file = new File(data_directory, "jamie.txt");
try {
    log_file.createNewFile();
} catch (IOException e) {
    // handle error
}

You will notice I am using the File(string, string) constructor to build up the path. This will join the separate parts together using the correct path separator for the platform (i.e. \ on Windows, / on *nix).

Upvotes: 4

AlexR
AlexR

Reputation: 115328

Java is cross-platform by definition. Write once, compile once, run everywhere. Your code will work on all java supported platforms.

Upvotes: 0

Related Questions