My Java app will detect file extension and open it in Windows using wordpad, like this :
public static Process Display_File(String File_Path)
{
String Command,Program,Suffix=File_Path.toLowerCase();
Process process=null;
if (Suffix.endsWith("txt") || Suffix.endsWith("json")) Program="C:\\Program Files (x86)\\Windows NT\\Accessories\\word_pad.exe ";
Command=Program+"\""+File_Path+"\"";
try { process=Runtime.getRuntime().exec(Command); }
catch (Exception e) { e.printStackTrace(); }
return process;
}
But it won't work on Mac, I know there is TextEdit.app on Mac, so how to change the above code to run it on Mac ?
After the change, it looks like this :
public static Process Display_File_On_Mac(String File_Path)
{
String Command,Program,Suffix=File_Path.toLowerCase();
Process process=null;
if (Suffix.endsWith("txt") || Suffix.endsWith("json")) Program="/Applications/TextEdit.app ";
Command=Program+"\""+File_Path+"\"";
try { process=Runtime.getRuntime().exec(Command); }
catch (Exception e) { e.printStackTrace(); }
return process;
}
But I got this error :
java.io.IOException: Cannot run program "/Applications/TextEdit.app": error=13, Permission denied
How to fix it ?
Starting macOS Catalina system applications moved to /System/Applicatyions folder: https://support.apple.com/HT210650
So, new path to TextEdit is /System/Applications/TextEdit.app/Contents/MacOS/TextEdit
On El-capitan, giving the below path worked for me:
Program="open /Applications/TextEdit.app/Contents/MacOS/TextEdit";
You can Navigate into the TextEdit.app folder from a terminal window and make sure you have the executable in the right place before trying it out.
Also, you need to change the setting of command like this:
Command = Program+ " "+File_Path;
Related
I'm trying to use tesseract to do OCR on an image in java. I realize there are wrappers like Tess4J that provide a bunch more functionality and stuff, but I've been struggling to get it set up properly. Simply running a one-line command with Runtime is really all I need anyways since this is just a personal little project and doesn't need to work on other computers or anything.
I have this code:
import java.io.IOException;
public class Test {
public static void main(String[] args) {
System.out.println(scan("full-path-to-test-image"));
}
public static String scan(String imgPath) {
String contents = "";
String cmd = "[full-path-to-tesseract-binary] " + imgPath + " stdout";
try { contents = execCmd(cmd); }
catch (IOException e) { e.printStackTrace(); }
return contents;
}
public static String execCmd(String cmd) throws java.io.IOException {
java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
When it's compiled and run directly from terminal, it works perfectly. When I open the exact same file in eclipse, however, it gives an IOException:
java.io.IOException: Cannot run program "tesseract": error=2, No such file or directory
What's going on? Thank you for any help.
Check the working folder in the run configuration for the Test class in Eclipse. I bet it's different from the one when you run the same program from a terminal.
I have a Java program, that on runtime, extracts some executables to a specific folder, and tries to run them. Of course, before running the executable, its permissions need to be changed. For that purpose, I am using the following piece of code:
public static void changePermissions(String filename,String path){
String[] cmd=new String[3];
cmd[0]="chmod";
cmd[1]="u+x";
cmd[2]=filename;
BetterRunProcess process=new BetterRunProcess();
process.runProcessBuilderInDifferentDirectory(cmd,path,1,0,0,"");
}
In the above code snippet,the variable path contains the path to the executable, and filename is the name of the executable. The line:
process.runProcessBuilderInDifferentDirectory(cmd,path,1,0,0,"");
executes the command "chmod u+x ...". On my own computer, the code works just fine, but when I run it on someone else's computer, the following error is thrown:
chmod: changing permissions of deviceQuery.out. Operation not permitted.
Can someone figure-out what might be the problem behind this?
Here is some more code, that might be helpful.
public void runProcessBuilderInDifferentDirectory(String[] cmd,String path,int printToConsole,int printToExternalFile,int append,String fileName){
ProcessBuilder builder;
if(cmd.length==1) builder=new ProcessBuilder(cmd[0]);
else if(cmd.length==2) builder=new ProcessBuilder(cmd[0],cmd[1]);
else if(cmd.length==3) builder=new ProcessBuilder(cmd[0],cmd[1],cmd[2]);
else if(cmd.length==4) builder=new ProcessBuilder(cmd[0],cmd[1],cmd[2],cmd[3]);
else builder=new ProcessBuilder(cmd[0],cmd[1],cmd[2],cmd[3],cmd[4]);
builder.directory(new File(path));
try {
Process pr=builder.start();
if(printToConsole==1) printToConsole(pr);
if(printToExternalFile==1) printToExternalFile(pr,fileName,append);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Thanks!
Run your java code from that user which has the permission for that file.
I have java desktop application where I have file upload and view feature.
Here is my code for opening a file
public static boolean open(File file) {
OSDetector osdetector = new OSDetector();
try {
if (osdetector.isWindows()) {
Runtime.getRuntime().exec(new String[]{"rundll32", "url.dll,FileProtocolHandler",
file.getAbsolutePath()});
return true;
} else if (osdetector.isLinux() || osdetector.isMac()) {
Runtime.getRuntime().exec(new String[]{"/usr/bin/open",
file.getAbsolutePath()});
return true;
} else // Unknown OS, try with desktop
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(file);
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace(System.err);
return false;
}
}
This is perfectly working in MAC OS but when I am running in windows 7 PC it won't open files.
Following are the error messages;
Adobe reader error: "There was an error opening this document. This file is already open or in use by another application"
Windows Photo viewer error message: "Windows photo viewer can't open this picture because the picture is being edited in another program"
Paint error message: "A sharing violation occurred while accessing ....."
Please help
Thank You
Windows can't cope with the idea of two programs using a file at once, presumably due to its DOS single-user origins. Make sure that when you save the file, you close it before you call your open() method.
So my problem here is that I'm not too sure how to print a set of commands to cmd. I have a batch file that runs a Minecraft server, and I need to be able to run commands through the command prompt that shows up when I run the batch file, which will in turn perform commands to the server.
Here is my code so far:
package com.Kaelinator;
import java.io.IOException;
public class ServerManager {
public static void main(String[] args){
try {
System.out.println("Opening");
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("cmd /C start /min " + "C:/Users/Owner/Desktop/rekt/Run.bat");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//System.out.println("Closing");
//process.destroy();
} catch (IOException e){
e.printStackTrace();
}
}
}
Yes, I understand that all this does so far is open the batch file. :P I am expecting something like this that I need to add to my code:
process.InputStream(command1);
But I am certain that there is more to it, something along the lines of bufferedWriters or something like that...
Whenever I try to get answers from Google, the answers always have a whole load of extra code, or have something completely different about them.
Thanks!
I'm creating a Java application using Netbeans. From the 'Help' Menu item, I'm required to open a PDF file. When I run the application via Netbeans, the document opens, but on opening via the jar file, it isn't opening. Is there anything that can be done?
m_aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Runtime rt = Runtime.getRuntime();
URL link2=getClass().getResource("/newpkg/Documentation.pdf");
String link=link2.toString();
link=link.substring(6);
System.out.println(link);
System.out.println(link2);
String link3="E:/new/build/classes/newpkg/Documentation.pdf";
try {
Process proc = rt.exec("rundll32.exe url.dll,FileProtocolHandler " + link3);
} catch (IOException ex) {
Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
The two outputs are as follows:
E:/new/build/classes/newpkg/Documentation.pdf
file:/E:/new/build/classes/newpkg/Documentation.pdf
Consider the above code snippet. On printing 'link',we can see that it is exactly same as the hard coded 'link3'. On using the hard coded 'link3' , the PDF file gets opened from jar application. But when we use link, though it is exactly same as 'link3', the PDF doesn't open.
This is most likely related to the incorrect PDF resource loading. In the IDE you have the PDF file either as part of the project structure or with a directly specified relative path. When a packaged application is running it does not see the resource.
EDIT:
Your code reveals the problem as I have described. The following method could be used to properly identify resource path.
public static URL getURL(final String pathAndFileName) {
return Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
}
Pls refer to this question, which might provide additional information.
Try out this:
m_aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
URL link2=Menubar1.class.getResource("/newpkg/Documentation.pdf");
String link=link2.toString();
link=link.substring(6);
System.out.println(link);
File file=new File(link);
System.out.println(file);
try {
desktop.open(file);
} catch (IOException ex) {
Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});