Sometimes we want to open a process & want to close that process only without effecting others using Java.
Below is one way where notepad is opened & only that notepad is closed without effecting others.
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
/**
* Below sample shows a way to open a Notepad,
* Add contents through Java or even you can add contents manually.
* But if you add contents manually then you have to save the file by yourself, else you will loose the contents
* once notepad is closed by the program. Currently, you will not get any warning even.
* Below code will close that notepad only which it opens, other applications will remain open.
* @author nitin
*
*/
public class Notepads {
public static void main(String[] args) {
Desktop d=Desktop.getDesktop();
try {
// d.open(new File("d:\\test.txt"));
String name = "d:\\test.txt";
String message = "Hello World!" + System.lineSeparator();
File f = new File(name);
if(!f.exists())
f.createNewFile();
Files.write(Paths.get(name), message.getBytes(), StandardOpenOption.APPEND);
Process pr = Runtime.getRuntime().exec("notepad " + name);
Thread.sleep(5000);
// Below line will cause all the notepad instances to be closed.
// Runtime.getRuntime().exec("taskkill /IM notepad.exe");
pr.destroy();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Below is one way where notepad is opened & only that notepad is closed without effecting others.
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
/**
* Below sample shows a way to open a Notepad,
* Add contents through Java or even you can add contents manually.
* But if you add contents manually then you have to save the file by yourself, else you will loose the contents
* once notepad is closed by the program. Currently, you will not get any warning even.
* Below code will close that notepad only which it opens, other applications will remain open.
* @author nitin
*
*/
public class Notepads {
public static void main(String[] args) {
Desktop d=Desktop.getDesktop();
try {
// d.open(new File("d:\\test.txt"));
String name = "d:\\test.txt";
String message = "Hello World!" + System.lineSeparator();
File f = new File(name);
if(!f.exists())
f.createNewFile();
Files.write(Paths.get(name), message.getBytes(), StandardOpenOption.APPEND);
Process pr = Runtime.getRuntime().exec("notepad " + name);
Thread.sleep(5000);
// Below line will cause all the notepad instances to be closed.
// Runtime.getRuntime().exec("taskkill /IM notepad.exe");
pr.destroy();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}