Java - Find absolute path of file - java

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.

Related

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.

getCanonicalPath returns a different path between different platforms

One of the lower methods in my code is getting the canonical path to the temp folder using the file.getCanonicalPath() function (File was defined as File file = new File("/tmp")). This works in linux and windows OS's, but on macOS, this function returns the following string - "/private/tmp" even though I have a tmp folder in my home directory and I don't have /private directory.
Any idea where does this "private" directory is coming from and why this method is not directing me to "/tmp" in macOS even though its accessible?
Note: if I create a random, non- existing dir File object (File file = new File("/random")) it will return the canonical path just fine.
A symbolic link, also termed a soft link, is a special kind of file
that points to another file, much like a shortcut in Windows or a
Macintosh alias. Unlike a hard link, a symbolic link does not contain
the data in the target file. It simply points to another entry
somewhere in the file system.
On macOS /tmp is symlinked to /private/tmp. The directory /private does exist and contains tmp inside it.

Java get current file name EXE

This is my first Stackoverflow question.
I searched across Google for getting the current file name in Java. Most of the sources tell users how to find the current file name if the file is a JAR file, but I'm asking for if the current file is an EXE file.
I saw one EXE answer in Get name of running Jar or Exe, but I don't think it worked.
I use the JSmooth EXE wrapper (launch4j somehow didn't work for me), and Java 8. Is there a straightforward solution to my question? Also, it's nice to explain how it works, or provide a link to the Java documentary about it.
EDIT: To clarify, let's say that I made a Java program and used a JAR wrapper, and I named the resulting EXE "test.exe". I want the Java program be able to give me the current directory of "test.exe", including the filename itself (test.exe).
ANOTHER EDIT: Just to clarify more, go onto your desktop, create a text file, and put some text in it. Save it, and change the text file to an EXE file. Then, try to open it. Windows will give an error. Notice how the title of the message dialog is the file path of the opened file. That is the type of output I want.
Thanks.
Per the JSmooth documentation,
JSmooth also makes some special variable accessible for your application.
Form Meaning
${EXECUTABLEPATH} Replaced by the path to the executable binary. For
instance, if the executable binary launched is located
at c:/program files/jsmooth/test.exe, this variable
is replaced with c:/program files/jsmooth
${EXECUTABLENAME} Replaced by the name of the executable binary. For
instance, if the executable binary launched is located
at c:/program files/jsmooth/test.exe, this variable is
replaced with test.exe
You set these in JSmooth under the "Environment Settings" (the last panel), which allows you to map the variable name. So,
MY_EXECUTABLEPATH=${EXECUTABLEPATH}
MY_EXECUTABLENAME=${EXECUTABLENAME}
In your application, you can get those with
String execPath = System.getProperty("MY_EXECUTABLEPATH");
String execName = System.getProperty("MY_EXECUTABLENAME");
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
}
}
This will print a complete absolute path from where your application has initialized. It is used to get only the DIRECTORY.
If you are using a .exe why do you not create a installer? You can use Inno Setup, this way you are able to specify where do you want to store your .exe, and get it from your application just passing your custom directory

ImageMagick/IM4J FileNotFoundException

I am trying to use IM4J (a Java wrapper for ImageMagick) to create thumbnails of JPEGs and it is my first experience (ever) with both libraries. Please note that this is a hard requirement handed to me by my tech lead (so please don't suggest to use anything other than an IM4J/ImageMagick) solution - my hands are tied on the technology choice here!
I am getting a FileNotFoundException on the and convert command which tells me I don't have one of these libraries (or both) setup correctly.
On my computer, here is my directory structure:
C:/
myApp/
images/ --> where all of my JPEGs are
thumbnails/ --> where I want ImageMagick to send the converted thumbnails to
imageMagickHome/ --> Where I downloaded the DLL to
ImageMagick-6.7.6-1-Q16-windows-dll.exe
...
In my Java project, I make sure that the IM4J JAR (im4java-1.2.0.jar) is on the classpath at runtime. Although I am required to use the 1.2.0 version of IM4J, I have the liberty to use any version of ImageMagick that I want. I simply chose this version because it seemed like the most current/stable version for my Windows 7 (32-bit) machine. If I should use a different version, please send me a link to it from the ImageMagick downloads page in your answer!
As for ImageMagick, I just downloaded that EXE from here and placed it in the folder mentioned above - I didn't do any installation, wizard, MSI, environment variable configuration, etc.
Then, in my Java code:
// In my driver...
File currentFile = new File("C:/myApp/images/test.jpg"); --> exists and is sitting at this location
File thumbFile = new File("C:/myApp/thumbnails/test-thumb.jpg"); --> doesnt exist yet! (destination file)
Thumbnailer myThumbnailer = new Thumbnailer();
myThumbnailer.generateThumbnail(currentFile, thumbFile);
// Then the Thumbnailer:
public class Thumbnailer
{
// ... omitted for brevity
public void generateThumbnail(File originalFile, File thumbnailFile)
{
// Reads appConfig.xml from classpath, validates it against a schema,
// and reads the contents of an element called <imPath> into this
// method's return value. See below
String imPath = getIMPathFromAppConfigFile();
org.im4java.core.IMOperation op = new Operation();
op.colorspace(this.colorSpace);
op.addImage(originalFile.getAbsolutePath());
op.flatten();
op.addImage(thumbnailFile.getAbsolutePath());
ConvertCmd cmd = new ConvertCmd();
cmd.setSearchPath(imPath);
// This next line is what throws the FileNotFoundException
cmd.run(op);
}
}
The section of my appConfig.xml file that contains the imPath:
<imPath>C:/myApp/imageMagickHome</imPath>
Please note - if this appConfig.xml is not well-formed, our schema validator will catch it. Since we are not getting schema validation errors, we can rule this out as a culprit. However, notice my file path delimiters; they are all forward slashes. I did this because I was told that, on Windows systems, the forward slash is treated the same as a *nix backslash, in reference to file paths. Believe it or not, we are developing on Windows
machines, but deploying to linux servers, so this was my solution (again, not my call!).
IM4J even acknowledges that Windows users can have trouble sometimes and explains in this article that Windows developers might have to set an IM4JAVA_TOOLPATH env var to get this library to work. I tried this suggestion, created a new System-wide environmental variable of the same name and set its value to C:\myApp\imageMagickHome. Still no difference. But notice here I am using backslashes. This is because this env var is local to my machine, whereas the appConfig.xml is a config descriptor that gets deployed to the linux servers.
From what I can tell, the culprit is probably one (or more) of the following:
I didn't "install" the ImageMagick EXE correctly and should have used an installer/MSI; or I need to add some other environmental variables for ImageMagick (not IM4J) itself
Perhaps I still don't have IM4J configured correctly and need to add more environmental variables
Could be the Windows/*nix "/" vs. "" issue from my appConfig.xml file as mentioned above
I'm also perplexed as to why I'm getting a FileNotFoundException on a file named "convert":
java.io.FileNotFoundException: convert
I assume this is a batch/shell file living somewhere inside the IM4J jar (since the only thing I downloaded for ImageMagick was the EXE). However, if I extract the IM4J jar I only see classes inside of it. I see "script generator" classes, so I assume these kick off before my cmd.run(op) call and create the convert file, and maybe that's what I'm missing (perhaps I need to manually kick off one of these generators, like CmdScriptGenerator prior to executing my Thumbnailer methods. . Or, maybe my download is incomplete.
Either way, I'm just not versed enough with either library to know where to start.
Thanks for any help with this.
Run the 'ImageMagick-6.7.6-1-Q16-windows-dll.exe' installer first to install the imagemagick libraries. Then make sure your environment path includes the location of the installed binaries ('convert.exe', 'mogrify.exe', etc)
Make sure u have Set the environment-variable IM4JAVA_TOOLPATH.

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