I want to open Notepad program in MS Windows by Java code to open my text file.
Pls help me to do that.
You can use the java.awt.Desktop if using Java 1.6, .txt is registered to the notepad and Desktop is supported:
if (!Desktop.isDesktopSupported()) {
System.err.println("Desktop not supported");
// use alternative (Runtime.exec)
return;
}
Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.EDIT)) {
System.err.println("EDIT not supported");
// use alternative (Runtime.exec)
return;
}
try {
desktop.edit(new File("test.txt"));
} catch (IOException ex) {
ex.printStackTrace();
}
this way you can open/edit files in a more OS independent way.
Runtime.getRuntime().exec("notepad c:/asd.txt");
where c:/asd.txt is the full path to your text file. If / doesn't work for you, use \\ instead.
If you have registered the .txt extension on your OS and your text file already exists then you can do even
Runtime.getRuntime().exec(new String[]{"cmd.exe","/c","text.txt"});
The advantage is it will take the program associated with .txt, what could be diferent from notepad.exe.
use the ProcessBuilder Class
Process p = new ProcessBuilder("notepad", "file.txt").start();
Related
I want to be able to open an application like internet, notepad, iTunes, and any other .exe file from use input.
Right now I got this;
(ext is the user input)
try
{
Process p = Runtime.getRuntime().exec(ext + ".exe");
}
catch(Exception e1){ }
This, however, only seems to be able to open notepad, is there any way I can make it so it can open any installed .exe file?
[NOTE]
I'm trying to do this from a java-window I created
For example this line runs Skype
Process p = Runtime.getRuntime().exec("C:/Program Files (x86)/Skype/Phone/skype.exe");
i got two questions.
Where is the directory the Method Runtime.getRuntime().exec() gets its resources from?
if i am calling Runtime.getRuntime().exec("notepad.exe"), why does it start the windows editor? Where does java gets the .exe source from?
based on this question, i have to let the user choose, if he wants to open a file in an editor, which editors he prefers, and wants to use. He only writes in something like notepad.exe or ultraedit.exe and the choosen file will be opened in the editor written down here. At the moment, i am opening a file with this Method
public void open(String path) {
try {
if(new File(path).exists())
Runtime.getRuntime().exec("notepad.exe " + path);
} catch (IOException e) {
e.printStackTrace();
}
}
So as you can see every file will be opened within the notepad. But i need to have something like this :
public void open(String program, String path) {
try {
if(new File(path).exists())
Runtime.getRuntime().exec(program + " " + path);
} catch (IOException e) {
e.printStackTrace();
}
}
So is there any possibility to open txt files in different editors, by just calling their
.exe file?
Where does java gets the .exe source from?
Its not about java. check the PATH environment variables in you Operating systems. It has the path for all the exe files.
Try this
1) open cmd
2) type c:\> echo %PATH%
the second will tell you the values of PATH variable
So is there any possibility to open txt files in different editors, by just calling their .exe file?
yes edit the PATH variable to include the path of you other editor's exe file ( use semicolon and then append the path to environment don't replace the existing string ), and the java program remains the same
Runtime.exec() gets its information from PATH. Any program found in there can be executed like you showed.
I have written a program that creates PDF documents. After creating, the PDF's must be opened so it can be printen.
i have the following code, but it only works if i launch from netbeans. Could anyone give me some pointers?
public void openPDF()
{
try {
System.out.println("Opening PDF");
File file = new File(pdfPath+pdfName);
String absolutePDFpath = file.getAbsolutePath().replace(""+(char)92,""+(char)92+(char)9);
System.out.println("Path = "+absolutePDFpath);
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + absolutePDFpath);
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(null, "Er is een fout opgetreden tijdens het openen van het PDF"
+ " document\nFoutcode: 0xFF05");
Logger.getLogger(PrintJob.class.getName()).log(Level.SEVERE, null, ex);
}
See Desktop.open(File) for a way to open a PDF across different platforms. Something like this..
File file = new File(pdfPath+pdfName);
Desktop.getDesktop().open(file);
If the app. needs to support Java 1.5 or earlier (before Desktop was available), stick with exec(), but implement all the recommendations of When Runtime.exec() won't.
There are a number of things that using a Process requires the programmer to do, for reliable running. That code does none of them.
Probably your code doesn't work because you don't specify environment variables. It should be something like this:
Runtime.getRuntime().exec("command to execute", env[]);
I want to open Notepad in my Java program. Suppose that I have one button if I click this button the notepad will appear.
I already have a file name and a directory.
How can I implement this case?
Try
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().edit(file);
} else {
// I don't know, up to you to handle this
}
Make sure the file exists. Thanks to Andreas_D who pointed this out.
(assuming you want notepad to open "myfile.txt" :)
ProcessBuilder pb = new ProcessBuilder("Notepad.exe", "myfile.txt");
pb.start();
Assuming you wish to launch the windows program notepad.exe, you are looking for the exec function. You probably want to call something like:
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("C:\\path\\to\\notepad.exe C:\\path\\to\\file.txt");
For example, on my machine notepad is located at C:\Windows\notepad.exe:
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("C:\\Windows\\notepad.exe C:\\test.txt");
This will open notepad with the file test.txt open for editing.
Note you can also specify a third parameter to exec which is the working directory to execute from - therefore, you could launch a text file that is stored relative to the working directory of your program.
Using SWT, you can launch any
If you want to emulate double-clicking on a text in windows, it's not possible only with a plain JRE. You can use a native library like SWT and use the following code to open a file:
org.eclipse.swt.program.Program.launch("c:\path\to\file.txt")
If you don't want to use a third-party lib, you should know and you know where notepad.exe is (or it's visible in PATH):
runtime.exec("notepad.exe c:\path\to\file.txt");
Apache common-exec is a good library for handling external process execution.
UPDATE: A more complete answer to your question can be found here
In IDE (Eclipse) it compains about "C:\path\to\notepad.exe C:\path\to\file.txt" .
So i have used the following which works for me keeping me and my IDE happy :o)
Hopefully this will help others out there.
String fpath;
fPath =System.getProperty("java.io.tmpdir")+"filename1" +getDateTime()+".txt";
//SA - Below launches the generated file, via explorer then delete the file "fPath"
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("explorer " + fPath);
Thread.sleep(500); //lets give the OS some time to open the file before deleting
boolean success = (new File(fPath)).delete();
if (!success) {
System.out.println("failed to delete file :"+fPath);
// Deletion failed
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String fileName = "C:\\Users\\Riyasam\\Documents\\NetBeansProjects\\Student Project\\src\\studentproject\\resources\\RealWorld.chm";
String[] commands = {"cmd", "/c", fileName};
try {
Runtime.getRuntime().exec(commands);
//Runtime.getRuntime().exec("C:\\Users\\Riyasam\\Documents\\NetBeansProjects\\SwingTest\\src\\Test\\RealWorld.chm");
} catch (Exception ex) {
ex.printStackTrace();
}
You could do this the best if you start notepad in command line with command: start notepad
String[] startNotePadWithoutAdminPermissions = new String[] {"CMD.EXE", "/C", "start" "notepad" };
Save array of string commands and give it like parametr in exec
Process runtimeProcess = Runtime.getRuntime().exec(startNotepadAdmin2);
runtimeProcess.waitFor();
My program successfully creates and fills a Excel(.xls) file. Once created, I would like the new file to open in the system's default program (Excel in my case). How can I achieve this?
For an older program where I wanted to open a txt file in Notepad, I used the following:
if (!Desktop.isDesktopSupported()) {
System.err.println("Desktop not supported");
// use alternative (Runtime.exec)
return;
}
Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.EDIT)) {
System.err.println("EDIT not supported");
// use alternative (Runtime.exec)
return;
}
try {
desktop.edit(new File(this.outputFilePath));
} catch (IOException ex) {
ex.printStackTrace();
}
When I try to use this code for an Excel file it gives me the following error:
java.io.IOException: Failed to edit file:C:/foo.xls
Suggestions?
Try to use Desktop.open() instead of Desktop.edit() :
Desktop dt = Desktop.getDesktop();
dt.open(new File(this.outputFilePath));
If Desktop.open() is not available then the Windows file association can be used :
Process p =
Runtime.getRuntime()
.exec("rundll32 url.dll,FileProtocolHandler " + this.outputFilePath);
You probably did the Runtime.exec incorrectly. Give this a look to see if that's the case.
If you just want to open an Excel file with Java, I'd recommend using Andy Khan's JExcel API. Perhaps using that with a Swing JTable will be just the ticket.
The most simple and efficient way.
Desktop.getDesktop().open(new File("inputFilePath"));