I'm making a program for mac that has it's own file extension .edul. I got it working so that when the program has already opened and you open the file it's load it, but when I try this when the program is yet running I don't get the event and it's not in the args.
I tried to change to com.apple.eawt.Application but unfortunately java.desktop doesn't export this class so this didn't work.
Desktop desktop = Desktop.getDesktop();
desktop.setOpenFileHandler(e -> {
try {
FileWriter fileWriter = new FileWriter(System.getProperty("user.home") + "/Desktop/test.txt");
fileWriter.write(e.getFiles().toString());
fileWriter.close();
} catch (IOException ignored) {
}
});
So I expect a file on my desktop that has the location of the file I opened before the program was running and when it's running and I open another file it's also shows on my desktop.
So after first file open:
[file/path/test.edul]
And on seconds file open:
[file/path/test2.edul]
I'm currently only getting:
[file/path/test2.edul]
So, the problem is that when you define a FileOpenHandler in the class which starts your fx application the FileOpenEvent is only thrown when the program is already running. So you should make a other main class that doesn't extends Application and the FileOpenEvent will be correctly thrown even when the application is still starting up.
Related
Im having trouble with using Desktop.getDesktop().open(). Im trying to run one java file from another one, using this code:
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class OpenFile {
public static void main(String[] args){
String program = "HelloWorld.java";
try {
Desktop.getDesktop().open(new File(program));
} catch(IOException e) {
System.out.println(program + " if not on the desktop");
}
}
}
I have a file called HelloWorld.java sitting on my desktop, but I'm getting this error:
Exception in thread "main" java.lang.IllegalArgumentException: The file: HelloWorld.java doesn't exist.
at java.awt.Desktop.checkFileValidation(Desktop.java:210)
at java.awt.Desktop.open(Desktop.java:270)
at OpenFile.main(OpenFile.java:10)
I'm on a Mac, so that may be the problem but I'm not sure. I'd appreciate any advice!
There are two issues that I see here.
You want to "run" a Java program, which is not the same as "opening" a Java file.
Even if you are trying to "open" a Java file using Desktop.getDesktop().open, this does not mean that getDesktop().open points to your "Desktop" folder from where you can open a file on your Mac's Desktop.
To execute your Java program, you need to first compile the Java program using the Java compiler. Then you would be able to "run" your program.
Runtime.getRuntime().exec("javac /Users/username/Desktop/HelloWorld.java");
Runtime.getRuntime().exec("java -classpath /Users/username/Desktop HelloWorld");
The Desktop.getDesktop().open(File file) method simply opens the selected file in the default application for that file type. For example, on a Mac, a text file would be opened by TextEdit.app.
Hope this helps!
I wrote a Java program some time ago that automatically opens a webpage before I get to work in the morning. I do this by calling a batch file from Java, which opens the webpage. This program worked great for about three or four months without any problems, but one day it just stopped working. I have tried opening the webpage from within Java as well instead of the batch file, but I consistently run into a problem. This is the process I use:
I exported my program as a runnable JAR and converted it to an EXE using Launch4j. In my Windows task scheduler I schedule it to run at 5:30am every morning.
My Java program calls the batch file that is stored on my desktop
The batch file opens Chrome and calls the webpage to open
When I run the Java program EXE manually (double-click from the desktop) it runs correctly, calls the batch file, and opens the webpage. However, when I try running the EXE from the Windows task scheduler it does not (visibly) open the webpage. It does appear to run Chrome in the background (according to the task manager/Process Explorer) but the webpage itself doesn't seem to open (I can tell because the webpage I open should be playing music, but I hear nothing).
This is the Java function I use to run the batch file:
public static void openWebpage() throws Exception {
String[] startupBat = {"cmd", "/c", "start", "/B", System.getProperty("user.home") + "\\Desktop\\WebpageStart.bat"};
ProcessBuilder pb = new ProcessBuilder(startupBat);
try {
webpage = pb.start();
} catch (IOException e) {
logWriter.write(tf.format(new Date()).toString() + " - Unable to start webpage");
}
if (webpage != null) {
try {
webpage.waitFor();
} catch (InterruptedException e) {
logWriter.write(tf.format(new Date()).toString() + " - Webpage startup interrupted");
} finally {
webpage.destroy();
}
}
}
And here are the contents of the batch file I use to start the webpage:
#echo off
start "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" http://www.myWebpage.com
Once again, everything works fine when I run the Java EXE manually, but when I try to run it from the task scheduler the webpage doesn't appear to open. What could cause this sort of behavior? What changes when the task scheduler runs a program vs. when it is manually run?
A few things to check
Which user is the scheduled task running as? Is it the same user as the one double clicking on the icon?
Have you changed your password recently? You might need to update the password on the scheduled task
Go to the windows event viewer, are there any errors in there?
This question already has answers here:
How to check if a file is open by another process (Java/Linux)?
(5 answers)
Closed 6 years ago.
I am trying to write an excel file in java, and saving it in a shared folder. but if the file currently open at any system by anyone, it is throwing an error. So is there any way that we can close an excel file via a java command?
How to delete/close open excel file. so you have to auto close the file before delete...
final File file=new File("E:\\book1.xlsx");
Runtime.getRuntime().exec(
"cmd /c taskkill /f /im excel.exe");
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.currentThread().sleep(2000);// you need to wait 1-2 sec to close file before delete
file.delete();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
If the file is actually open in someone's window (like you would open a ms word doc), then it's not going to be possible to close the file on their machine from a java program. If you just need to one-time update that file, I'd recommend creating another file with a different name, and then manually replacing the contents of the desired destination with the contents of the file that you programatically create.
Depending on the way the file is opened, you may be able to execute the command net files <id> /close via Runtime.exec(). You can also combine the psexec command to close files on remote computers.
This answer seems to describe a similar situation, you just need to make java run the commands:
https://superuser.com/questions/643916/remotely-close-open-shared-files
Hi how can I get rid of C drive access with java codes I can do this with manual but I want to do this with java codes
here is my code
File file=new File("C:\\Windows\\b.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
System.out.println("file not created and");
e.getMessage();
e.printStackTrace();
}
And my exceptions
java.io.IOException: Access is denied
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1006)
at tekrar.Write.main(Write.java:26)`
you need to run the program as an administrator to edit the C:\Windows folder. this is a system folder that you should not access.
You cannot write anything in the system folder without administrator privileges in windows. As I understand you cannot request administrator access from within a Java program and you'll have to RUN the application in admin mode.
See this question for some tips: Run Java file as Administrator with full privileges
P.S. Do you really need to write into the windows folder?
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.