I have a set of unit test cases that depend on a test.properties file. When I run the tests under Mac OSX or Linux using Maven ('mvn test'), they work fine. But when running under Windows 7, they can't find the file unless I copy it directly to the class folder. The code to return the properties is the following two methods:
private void loadProperties() {
try {
properties.load(HibernateTestCase.class.getResourceAsStream(getPropertiesFilePath()));
} catch (Exception ioExc) {
ioExc.printStackTrace();
}
}
private String getPropertiesFilePath() {
return File.separator + "test.properties";
}
What's the real deal here? Is it all about the file path being set wrong somewhere? Thanks in advance!
The separator in resource names is always '/'. File.separator varies from platform to platform (on UNIX variants it will generally be /, on Windows it will not).
Either your classpath is different, or you're using a different classloader with different resolution characteristics.
Related
I'm trying to execute java to run a JAR file from an Azure function, but it seems like the java PATH variable isn't defined or something because Azure can't seem to find it. Code below:
Process proc = new Process();
try
{
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.FileName = "java.exe";
proc.StartInfo.Arguments = "-jar file path and some more arguments";
proc.Start();
proc.WaitForExit();
if (proc.HasExited)
log.Info(proc.StandardOutput.ReadToEnd());
log.Info("Java Success!");
}
catch (Exception e)
{
log.Info("Java Fail");
log.Info(e.Message);
}
Even if I remove the proc.StartInfo.Arguments or tell it to use java.exe instead of java I still get the same error, below:
[Info] The system cannot find the file specified
Is calling java not supported in Azure functions?
OK figured this out. So far, the best way is to fully qualify the path to java.exe...
so I changed
proc.StartInfo.FileName = java.exe";
to
proc.StartInfo.FileName = "D:\\Program Files (x86)\\Java\\jdk1.8.0_73\\bin\\java.exe";
You can figure out the full path to Java using KUDU, which is https://[yourFunctionName].scm.azurewebsites.net/
If you click on Tools->DebugConsole, you can browse until you find where Java is located.
Note hard coding the path to Java is probably a bad idea so you should probably use application settings.
Edit Below is a link to a GitHub Repo with my final project. The project does some other stuff, but you can see where I call Java to execute the Batik JAR.
https://github.com/osuhomebase/SVG2PNG-AzureFunction
As of September 2022,
proc.StartInfo.FileName = java.exe";
Worked fine for me. It appears the Azure Function Environment has the JDK installed and the JAVA PATH variable set.
the java code is
String SCRIPT_PATH = "D:\\codes\\Python\\StockDataAnalysis\\MatGraph.py";
try {
Jep jep = new Jep();
jep.runScript(SCRIPT_PATH);
} catch (Exception ex) {
ex.printStackTrace();
}
and it throws exception:
ImportError: No module named site
Python is no doubt installed correctly, for I can run python project on PyCharm. Jep is also set correctly, with lib path added to the PATH in windows System
You could try creating instance of Jep like so:
new Jep(false, path);
where as per javadoc (https://github.com/mrj0/jep/blob/master/src/jep/Jep.java#L299):
#param interactive
whether {#link #eval(String)} should support the slower
behavior of potentially waiting for multiple statements #param includePath
a path of directories separated by File.pathSeparator that
will be appended to the sub-intepreter's sys.path
This approach worked for me in similar case. In my case path was pointing to a directory
...virtualenv\projectname\Lib\site-packages
created for my virtual env where all my python libs for my project are stored.
Please notice that you need to install jep inside of that virtual env first in order to make it work.
I made a little program and it worked fine, but now. First, it mux the xml chapter file in the mkv file, so we get a muxed mkv file. Some day ago I updated java to 1.7.21 and I think this is the problem why it is not working now. It's a little strange, but when I run in netbeans everything is fine, but when I build and I run the .jar file, it is not working. It create the xml file, but not mux in the mkv file (and because not muxed not delete the xml file). Here is the code: (filename=xml file path; mkv=mkv file path)
public void muxing() {
try {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("c:\\Program Files\\MKVtoolnix\\mkvpropedit.exe --chapters \""+filename+"\" \""+mkv+"\"");
if (p.waitFor()==0) {
File xmlfile=new File(filename);
xmlfile.delete();
}
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
The program worked with java 1.6 and I think with 1.7.17 too. Win7 32bit. Sorry for my bad English.
Oracle has made breaking changes to Runtime.exec() in Java 7 update 21 (and 6 update 45).
If the program name contains spaces, you need to specify command and arguments in an array:
Process p = Runtime.getRuntime().exec(new String[] {
"C:\\Program Files\\MKVtoolnix\\mkvpropedit.exe",
"--chapters", "\""+filename+"\"", "\""+mkv+"\""});
Another option is to use java.lang.ProcessBuilder:
Process p = new ProcessBuilder("C:\\Program Files\\MKVtoolnix\\mkvpropedit.exe",
"--chapters", "\""+filename+"\"", "\""+mkv+"\"").start();
As stated by Oracle:
Applications that need to launch programs with spaces in the program name should consider using the variants of Runtime.exec that allow the command and arguments to be specified in an array.
Alternatively, the preferred way to create operating systems processes since JDK 5.0 is using java.lang.ProcessBuilder. The ProcessBuilder class has a much more complete API for setting the environment, working directory and redirecting streams for the process.
From my application written in java I want to open a folder, using the operating system file explorer.
I use Desktop.open(new File(path))
This works fine on windows, but on ubuntu 11.10 (linux) it doesn't work.
Using the Desktop.open to open a file does work, both on ubuntu and windows.
Using a step in between:
File fPath=new File(fPath)
and testing it with fPath.exists() and fPath.isDirectory() both gives true.
using the Desktop.open(new File(path)) gives me this exception:
java.io.IOException: Failed to show URI:file:/and/here/the/path/I/use/
at sun.awt.X11.XDesktopPeer.launch(Unknown Source)
at sun.awt.X11.XDesktopPeer.open(Unknown Source)
at java.awt.Desktop.open(Unknown Source)
I was not able to test this on an apple computer yet, but I hoped the Desktop.open(new File(path)) was system independent.....
by the way, the complete code:
Desktop desktop = null;
// Before more Desktop API is used, first check
// whether the API is supported by this particular
// virtual machine (VM) on this particular host.
if (!Desktop.isDesktopSupported()) {
// show Error
return;
}
desktop = Desktop.getDesktop();
String path = "here the path ";
// by the way: I use System.getProperty("file.separator") as file seperator
try {
File fPath=new File(path);
if(!fPath.exists()){
// show Error
return;
}
if(!fPath.isDirectory()){
// show Error
return;
}
desktop.open(new File(path));
} catch (IOException e) {
log.severe(e.getMessage());
e.printStackTrace();
// show Error
return;
}
Some extra information:
OS: Linux (3.0.0-16-generic - amd64)
Java: 1.6.0_30-b12
Java home: /opt/java/64/jre1.6.0_30
I had the same problem. But in my case it was Ubuntu 18.04 and java 1.8.0_161-b12
In Windows 10, everything is working fine. But on Ubuntu
Desktop.getDesktop().open(new file)
the program stopped responding.
I decided to wrap the call in the executor:
private ExecutorService executorService;
BasicThreadFactory factory = new BasicThreadFactory.Builder()
.namingPattern("YourPatternIndeficator")
.build();
executorService = Executors.newSingleThreadExecutor(factory);
if (Desktop.isDesktopSupported()) {
File myFile = new File(path);
executorService.execute(() -> {
try {
Desktop.getDesktop().open(myFile);
} catch (IOException e) {
e.printStackTrace();
}
});
}
I was running into what sounds like the same issue on Mint 13. From what I can tell, changes to mime handling for opening directories has broken the java Desktop api. I was able to work around the problem by editing
~/.local/share/applications/defaults.list
and adding this line
x-directory/normal=nautilus.desktop
I'm running Mint 13 Cinnamon with java version "1.7.0_05"
I can't confirm the error. I took your code and constructed a main method around it, and everything works as expected. I don't exactly know where the default applications are set (in my case PCMan was opened instead of usual Nautilus, but it should fulfil its purpose in the end).
Over at java.awt.Desktop.open doesn’t work with PDF files? I have found a link pointing to an issue in Suns (Oracles) bug tracker stating that the method for opening files using AWT isn't reliable even on Windows. Maybe you should think of alternative ways of opening such applications. Furthermore AWT is deprecating soon almost for sure.
If you are utilizing SWT in your application, you could use org.eclipse.swt.program.Program.
I was running into the same issue and decided to give Java 7 a whirl. I'm running java version "1.7.0_147-icedtea" on Ubuntu 11.10_x64 and am able to open file locations in Nautilus quite happily now.
I have the same issue on my Linux Mint (and not in Windows).
That link helped me :
Troubles with java.awt.Desktop browse() method.
This seems to work on my Linux Mint-KDE.
I changed the line
Desktop.getDesktop().desktop.open(new File("/home/user/mypath"));// this throws IOException: Failed to show URI (except in Windows)
with
Desktop.getDesktop().desktop.open(new File("///home/user/mypath"));// this launches Dolphin
or with
Desktop.getDesktop().desktop.open(new File(new URI("file:///home/user/mypath").getPath()));// this launches Dolphin
Dolphin was launched with my folder "mypath". But I found no way to open a file like a pdf or txt on my Linux while it works on Windows with the first code.
(Java 1.8.0_25, Netbeans 8.02, Linux Mint 12 KDE)
I have the issue with Kubuntu 18.04 and java 11. It was solved with
sudo apt install libgnome2-0 gvfs
see https://bugs.launchpad.net/ubuntu/+source/openjdk-8/+bug/1574879/comments/5 for details. java.awt.Desktop works with Gnome not with KDE.
How to copy a file from Linux System to Windows system using Java program?
Thanks for your help.
I want to copy file from linux : /inet/apps/test.java to windows System1: C:\apps\test
We can use following program to copy
public static void copyFiles(String fromFile, String toFile ){
FileInputStream from = null;
FileOutputStream to = null;
try {
from = new FileInputStream(fromFile);
to = new FileOutputStream(toFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1)
to.write(buffer, 0, bytesRead); // write
}catch(Exception e){e.printStackTrace();}
finally {
if (from != null)
try { from.close();} catch (IOException e) {}
if (to != null)try {to.close();} catch (IOException e) {}
}
}
This program is running on linux.
so fromFile = /inet/apps/test. What will be the toFile path. If i use simply C:\apps\test then how applicaiton recognise the target as System1.
Java makes no diffeence between Windows and Linux files. So, as long as you have access to both filesystem in the computer your java program is running, you can just copy them.
I think you are asking about some
properties for the program.
In that case the properties, should
be configurable. You can keep the
properties file in the same
directory as your Java program or in
the class path.
The property file might look like :
windows.filepath = C:\user\somefile.txt
unix.filepath = /inet/apps/test.txt
So when you port environments. You
don't need to change the properties.
If you are asking about how to port
test.java to windows, then just copy
the file to JAVA_HOME directory on
windows and then you are good to go.
Or If you have a Dual boot system.
You can access your linux drive
from windows, but not the other
way around.
If the Unix system has the Window file system cross-mounted (e.g. via an SMB share), you should be able to find the Unix pathname that corresponds to the Windows destination and copy as you are currently doing.
Otherwise, you will need to use a file transfer protocol of some kind to copy the file.
There's no Java magic that allows you to magically write files to a different computer. The operating system has to be set up to allow this to happen.
FOLLOW UP - you asked:
I have no thought about the magic. So my question was how to copy a file from Windows to Linux. Normally we do FTP on unix Without mounting or we use FileZilla tool to transfer happens. Here if we want to do same thing though java then how to do that?
I don't know how I can say this differently to make you understand, but here goes:
Your choices in Java are basically the same:
You can use FTP. For example on the destination machine, turn pathname of the source file into a "ftp://..." URL, and use java.net.URL.connect() to pull it. There are probably 3rd-party Java libraries that you can use to "push" the file to a FTP server.
If your OS is setup with the file systems cross-mount, you can do a regular file copy, much as your code does.
You can use java.lang.System.exec(...) to run some Windows specific command line utility to do the copying.
In all cases, you will need to figure out how to map pathnames between the Windows and Linux worlds.
You can try the copy() method of the java.nio.file.Files class, of course we assume that your application can access both the path on Linux and Windows either by mapping the folders or something similar. For example
Files.copy(Paths.get(source), Paths.get(destination), StandardCopyOption.REPLACE_EXISTING, COPY_ATTRIBUTES);