Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle ~ in file paths

Tags:

java

I'm writing a simple command line Java utility. I would like the user to be able to pass in a file path relative to their home directory using the ~ operator. So something like ~/Documents/...

My question is is there a way to make Java resolve this type of path automatically? Or do I need to scan the file path for the ~ operator?

It seems like this type of functionality should be baked into the File object. But it doesn't seem to be.

like image 735
Karthik Ramachandran Avatar asked Aug 23 '11 15:08

Karthik Ramachandran


People also ask

How do I use file paths?

To view the full path of an individual file: Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document.

How do you explain a file path?

A file path specifies the location of a file inside a web folder structure. Its like an address of a file which helps the web browser to access the files. File paths are used to link external resources such as images, videos, style sheets, JavaScript, displaying other web pages etc.

What does \\ mean in Windows path?

They indicate that the path should be passed to the system with minimal modification, which means that you cannot use forward slashes to represent path separators, or a period to represent the current directory, or double dots to represent the parent directory.


1 Answers

A simple path = path.replaceFirst("^~", System.getProperty("user.home")); when it is gotten from the user (before making a File out of it) should be enough to work in most cases - because the tilde is only expanded to a home directory if it is the first character in a directory section of a path.

like image 115
ratchet freak Avatar answered Sep 24 '22 00:09

ratchet freak