Opening file in current directory in java with file protocol - java

I have a license agreement file that needs to be open in default browser.
The file lies in installation folder itself.
I am doing it in java with awt as like this which is working fine:
Desktop d=Desktop.getDesktop();
d.browse(new URI("file://D:/OMS-Install/OMS/oms_license.txt"));
But since the entire folder can be placed anywhere on windows drive, at run time I need to consider the current directory. How can I achive this with Java & Default browser of AWT.
Doing it as there is a requirement. I would have otherwise followed many other options to accept terms and conditions.
Edit
Adding working code:
String path=new File("OMS/oms_license.txt").getAbsolutePath();
File license=new File(path);
URI urlLicense = license.toURI();
d.browse(urlLicense);

You can use Class.getResource() to retrieve the URL of something on the classpath.
Something along the lines of
URL license = getClass().getResource("/OMS/license.txt");

You can convert get file in current directory and calculate its absolute path
new File("./OMS/oms_license.txt").getAbsolutePath()

Related

How to Set a Path to Create Directory

This question header isn't the best, but I am trying to create a directory from the person's computer in java, then when a button is clicked, to navigate to that created directory and create a file. I just need to get the path then create the directory. Here is a sample:
File theDir = new File("Users/" + System.getProperty("user.name") + "/InfoSaveFiles");
if (!theDir.exists()) {
if (theDir.mkdirs()) {
}
}
The only problem is that when I run this, (from a compiled jar file or from my IDE), it just creates a directory Users/(name)/InfoSaveFiles instead of navigating to that particular path and creating the directory InfoSaveFiles as I would like.
How can I make it go to the specified path, then create the directory?
If you want to are using that file path, it will look for Users/(name)/InfoSaveFiles in the present working directory, in case of IDE, the root of the project file. So, if you add a slash / before it, like '/Users/(name)/InfoSaveFiles`, then it will look for the hierarchy from the root of the current heirarchy. In case of windows, from the drive you're running the program.
For example, if you set the file path with slash before it and you're running the program in the E:// drive, then the program will look for Users/(name)/InfoSaveFiles in that drive, and will create the hierarchy if not exists.
So, if you want to do that in specific drive, you need to mention that too at the front of that file path.
For Linux, starting with / indicates the root directory. So you can achieve it in linux giving the current file path you've mentioned with an added / in the front. It will look for that path from the root directory then.
Hope that answers your question.

System.getProperty("user.dir") alternative

I would like to write JSon files in my Java Application, it works perfectly in my IDE but as soon as I move the directory, the system fails to write the file. I eventually found the problem : The line System.getProperty("user.dir") returns a bad path.
The files are located in C:\wamp\www\myProject during development. Here is my code at the moment :
String url = System.getProperty("user.dir") + "\\src\\json\\Crc.json";
//Returns "C:\wamp\www\myProject\src\json\Crc.json"
After moving my project to C:\Users\myUser\Desktop :
String url = System.getProperty("user.dir") + "\\src\\json\\Crc.json";
//Returns "C:\Users\myUser\src\json\Crc.json"
I would like to have a way to find where my project directory is on the computer at anytime. Do you guys have a solution ?
The C:\wamp\www\myProject folder is just a random place on your hard disk.
Java supports 3 generic places to look for resources:
the current working directory. this is where your command prompt is and what System.getProperty("user.dir") returns, but you cannot rely on that beeing somehow related to any cretain place in the file system, especially not related to the project structure on your own system.
You should only use that if your program has a command line interface and looks for some default file name to work with.
the user home This is what you get when calling System.getProperty("user.home"). On Unix this resoves to $HOME and on Windows to %USERPROFILE%.
This is the best place for files changed at runtime or holding user specific content.
the own code location. Resources in the same package as your class are accessed with getClass().getResource("filenameWithoutPath") But usually you place resources in a special folder in the application root and access it like this: getClass().getResource("/relative/path/from/src/root/filenameWithoutPath").
In your IDE this special folder should be Project/src/main/resources (according to the maven Standard Directory Layout
This is appropriate for some global configurations that you change when creating the delivery package.

Sharing a Java Object Stream

I've got a project to do with 2 other classmates.
We used Dropbox to share the project so we can write from our houses (Isn't a very good choice, but it worked and was easier than using GitHub)
My question is now about sharing the object stream.
I want to put the file of the stream in same dropbox shared directory of the code.
BUT, when i initialize the file
File f = new File(PATH);
i must use the path of my computer (C:\User**Alessandro**\Dropbox)
As you can see it is linked to Alessandro, and so to my computer.
This clearly won't work on another PC.
How can tell the compiler to just look in the same directory of the source code/.class files?
You can use Class#getResource(java.lang.String) to obtain a URL corresponding to the location of the file relative to the classpath of the Java program:
URL url = getClass().getResource("/path/to/the/file");
File file = new File(url.getPath());
Note here that / is the root of your classpath, which is the top of the directory containing your class files. So your resource should be placed inside the classpath somewhere in order for it to work on your friend's computer.
Don't use absolute paths. Use relative paths like ./myfile.txt. Start the program with the project directory as the current dir. (This is the default in Eclipse.) But then you have to ensure that this both works for development and for production use.
As an alternative you can create a properties file and define the path there. Your code then only refers to a property name and each developer can adjust the configuration file. See Properties documentation.

Java - Find absolute path of file

I need to find the path to the user's vlc.exe file.
How can I do this?
I read this http://docs.oracle.com/javase/tutorial/essential/io/find.html and tried using code like
PathMatcher match = FileSystems.getDefault().getPathMatcher("glob:vjlc.{exe, jpg, png}");
Path filename = FileSystems.getDefault().getPath("vjlc.exe","");
if(match.matches(filename))
{
System.out.println(filename);
}
and
File fil = new File("vlc.exe");
System.out.println( fil.getAbsolutePath() );
neither of which worked
I believe you are trying to do something that is not quite right.
First, you're assuming that vlc.exe exists on the local machine. But what happens if it doesn't?
Second, what happens if VLC decides at some point (new build comes out, or upgrade) to change the exe file name to vlc2.exe?
To deal with this kind of dependency, I suggest you'll pass the vlc file location as a program argument to the main() method.
This way, you can create a batch file that tries to locate the vlc.exe path, and pass it through to the java program.
Another alternative, is to setup an environment variable, that will be set up during the installation of your java application. The installation can search for vlc.exe path, or have the user to set it up. Once the variable is set, the java program can read it from the system arguments (see this example).
A third way is to have a setting files (*.ini like), that will contain the vlc exe path. You can then have the file modified according to the relevant path, and have the java program read from it (as property file). The file can be auto generated too, during the installation process, or manually edited post installation.
You can use getAbsolutePath() function.
I think you're looking for ways of searching for the vlc.exe executable on the PATH. If so, something like the following should help:
String path = System.getenv("PATH");
String pathSeparator = System.getProperty("path.separator");
for (String pathElement : path.split(pathSeparator)) {
File file = new File(pathElement, "vlc.exe");
if (file.isFile()) {
// vlc.exe exists in this location.
}
}
When a user runs VLC installer to install VLC media player under Windows, the installer creates a Windows registry key entry HKLM\SOFTWARE\VideoLAN\VLC\InstallDir. You can retrieve the path stored in the key using Java as follows:
http://www.davidc.net/programming/java/reading-windows-registry-java-without-jni
read/write to Windows Registry using Java
If the HKLM\SOFTWARE\VideoLAN\VLC\InstallDir key is present, you know VLC is installed. If the user decides to install VLC at a different directory than what is suggested by VLC installer as default, the key will be able to tell you that.
This only works when the user installs VLC through its installer. But, it won't work if the user simply extracts VLC from its zip distribution file since this approach won't touch the Windows registry.

File paths in Java (Linux)

I have created a Java application that loads some configurations from a file conf.properties which is placed in src/ folder.
When I run this application on Windows, it works perfectly. However when I try to run it on Linux, it throws this error:
java.io.FileNotFoundException: src/conf.properties (No such file or directory)
If you've packaged your application to a jar file, which in turn contains the properties file, you should use the method below. This is the standard way when distributing Java-programs.
URL pUrl = this.getClass().getResource("/path/in/jar/to/file.properties");
Properties p = new Properties();
p.load(pUrl.openStream());
The / in the path points to the root directory in the jar file.
Instead of
String PROP_FILENAME="src/conf.properties";
use
String PROP_FILENAME="src" + File.separator + "conf.properties";
Check the API for more detail: http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html
I would also check what your current working directory is if your path to that file is relative. You just need to make a File test = new File("."); and then print that files canonical path name.
If you are referencing any other locations like user.dir or something to that effect by using System.getProperty(), you'll want to at least verify that the directory you are using as the relative root is where you think it is.
Also, as Myles noted, check the slashes used as file path separators. Although you can always use the "/" and it works.
And if you are referencing the path absolutely, you'll have trouble going between one OS and another if you do something silly like hard-code the locations.
What you want to do is check out System.getProperties() and look for file.separator. The static File.pathSeprator will also get you there.
This will allow you to build a path that is native for whatever system you're running on.
(If indeed that is the problem. Sometimes I like to get the current directory just to make sure the directory I think I'm running in is the directory I'm really running in.)
Check your permissions. If you (or rather, the user that the Java process is running under) doesn't have appropriate permissions to read the file, for example, you would get this error message.
This is a typical Windows -> Linux migration problem. What does ls -l src/conf.properties show when run from a prompt?
Additionally, check capitalisation. Windows isn't case-sensitive, so if the file was actually called e.g. CONF.properties it would still be found, whereas the two would be considered different files on Linux.
You should check the working directory of your application. Perhaps it is not the one you assume and that's why 'src' directory is not present.
An easy check for this is to try the absolute path (only for debugging!).
I would check your slashes, windows often uses '\' vs linux's '/' for file paths.
EDIT: Since your path looks fine, maybe file permissions or executing path of the app is different?
check your slashes and colons
in my case i set my PS1 to following value
PS1='\n[\e[1;32m]$SYSNAME(\u)#[\e[1;33m]\w [\e[1;36m](\d \T) [!]\e[0m]\n\$ '
i am trying to read from the env .such as system.getenv
Java was throwing exception
java.lang.IllegalArgumentException: Malformed \uxxxx encoding
Try the double slash, after doing things in JBoss I often had to refactor my code to use the double slashes

Categories

Resources