I try to run the *.bat files of derby, but I can't do this.
I want to run the "startNetworkServer.bat" and "ij.bat" using by java code.
I try to write some simple code but it not working.
package dbconnect;
import java.io.IOException;
public class RunDerbyTools {
public static void main(String[] args) {
String pathIj, pathStartNetwork, pathStopNetwork;
pathIj = "C:/MyWorkSpace/MyDBProject/db/bin/ij.bat"; // running ij tool
// running network
pathStartNetwork = "C:/MyWorkSpace/MyDBProject/db/bin/startNetworkServer.bat";
// stop network
pathStopNetwork = "C:/MyWorkSpace/MyDBProject/db/bin/stopNetworkServer.bat";
try {
Process pStartNetwork = Runtime.getRuntime().exec(pathStartNetwork);
} catch (IOException e) {
e.printStackTrace();
}
try {
Process pPathIj = Runtime.getRuntime().exec(pathStartNetwork);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
Using Java program I am opening an external application( for example: notepad). How can i get coordinates/location of external application for screen capture/screen-shots.
I can take screen-shots of the whole window, but not for a particular application.
I have already tried "Robot" for screen capturing but not able to capture a particular area as I am not able to find the location and size of the application window.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
public class AppCheck {
public static void main(String[] args) {
System.out.println("***********************");
try {
System.out.println("Opening notepad");
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("notepad");
try {
int count=0;
while(process.isAlive())
{
System.out.println("process name : " + process.getClass().getName());
Field f = process.getClass().getDeclaredField("handle");
f.setAccessible(true);
long handl = f.getLong(process);
System.out.println("Process ID : " + handl);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Closing notepad");
process.destroy();
} catch (Exception ex) {
System.out.println(ex);
}
System.out.println("************************************");
}
}
i have this simple code in java that shutdown the pc. What can i add to run this at Windows StartUp?
import java.io.IOException;
import java.io.OutputStream;
public class Spegni {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec("C:\\WINDOWS\\system32\\cmd.exe");
OutputStream os = process.getOutputStream();
os.write("shutdown -s -f -t 0\n\r".getBytes());
os.close();
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
start, run:
shell:startup
and then place the shortcut there. Happy trolling.
I am doing a small project for my girlfriends grandparents, that have a hard time using a computer so I thought I would be able to write something that might fix their problem. Here is the code first off:
import java.io.IOException;
public class OpenWordPad {
public static void main(String[] args) {
try {
System.out.println("Opening WordPad");
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("wordpad");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Closing WordPad");
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
}
}
(had to indent some so sorry if it is a little wonky)
When I put notepad in the process line it works fine but when I put in wordpad it freaks out. I want to be able to open wordpad so I can put it on their computer. Any suggestions?
For that you can use runTime.exec("write"):
import java.io.IOException;
public class OpenWordPad {
public static void main(String[] args) {
try {
System.out.println("Opening WordPad");
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("write"); // <--- here
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Closing WordPad");
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
}
}
opens WordPad.
I'm trying to prevent the launching multiple instances of a java application by binding a ServerSocket.
Currently I'm executing it in my main as seen below:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(65535, 10);
showFrame();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
It isn't working as in Eclipse I can still open two instances of the application.
There are some crons of using network socket.
What if the socket is used by other apps?
What if there is warning from firewall, which comes with some anti-virus?
Using an exclusive locked file seems to be more reliable.
AppLock.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
// http://jimlife.wordpress.com/2008/07/21/java-application-make-sure-only-singleone-instance-running-with-file-lock-ampampampampamp-shutdownhook/
public class AppLock {
private static File f;
private static FileChannel channel;
private static FileLock lock;
public static boolean lock() {
try {
String directory = Utils.getUserDataDirectory();
String fileName = "jstock.lock";
Utils.createCompleteDirectoryHierarchyIfDoesNotExist(directory);
f = new File(directory + fileName);
// Do we need these code?
//if (f.exists()) {
// f.delete();
//}
channel = new RandomAccessFile(f, "rw").getChannel();
lock = channel.tryLock();
if(lock == null) {
channel.close();
return false;
}
} catch (FileNotFoundException ex) {
log.error(null, ex);
} catch (IOException ex) {
log.error(null, ex);
}
return true;
}
public static void unlock() {
// release and delete file lock
try {
if (lock != null) {
lock.release();
channel.close();
f.delete();
}
} catch(IOException e) {
log.error(null, e);
}
}
private static final Log log = LogFactory.getLog(AppLock.class);
}
An usage example
public static void main(String args[]) {
if (false == AppLock.lock()) {
System.exit(0);
}
installShutdownHook();
...
}
private static void installShutdownHook() {
Runnable runner = new Runnable() {
#Override
public void run() {
AppLock.unlock();
}
};
Runtime.getRuntime().addShutdownHook(new Thread(runner, "Window Prefs Hook"));
}
Note, I pick the code snippet from an open source project : AppLock.java
Enforce one instance of a program running with a ServerSocket Lock
Java Code. Put this into a file called Main.java:
import java.net.*;
import java.io.*;
public class Main{
public static void main(String args[]){
ServerSocket socket = null;
try {
socket = new ServerSocket(34567);
System.out.println("Doing hard work for 100 seconds");
try{ Thread.sleep(100000); } catch(Exception e){ }
socket.close();
}
catch (IOException ex) {
System.out.println("App already running, exiting...");
}
finally {
if (socket != null)
try{ socket.close(); } catch(Exception e){}
}
}
}
Compile and run it
javac Main.java
java Main
Test it in a normal case:
Run the program. You have 100 seconds to run the program again in another terminal, it will fall through saying its already running. Then wait 100 seconds, it should allow you to run it in the 2nd terminal.
Test it after force halting the program with a kill -9
Start the program in terminal 1.
kill -9 that process from another terminal within 100 seconds.
Run the program again, it is allowed to run.
Conclusion:
The socket occupation is cleaned up by the operating system when your program is no longer operating. So you can be sure that the program will not run twice.
Drawbacks
If some sneaky person, or some naughty process were to bind all of the ports, or just your port, then your program will not run because it thinks its already running.
I need to read a bunch of binary files from a Java script running on Windows.
However, the folder that the files are in has limited permissions. I (i.e. my Windows username) have permissions to read them, but the user that Java runs as (this is part of a web application) does not. If I pass my own username and Windows network password into Java at runtime, is there a way I can read those files using my own permissions rather than the web user's?
(Note that this is NOT happening over the web; this is a one-time import script running in the context of a web application.)
You could create a network share and then connect via jCIFS
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFileInputStream;
public class Example
{
public static void main(String[] args)
{
SmbFileInputStream fis = null;
try
{
fis = new SmbFileInputStream("smb://DOMAIN;USERNAME:PASSWORD#SERVER/SHARE/filename.txt");
// handle as you would a normal input stream... this example prints the contents of the file
int length;
byte[] buffer = new byte[1024];
while ((length = fis.read(buffer)) != -1)
{
for (int x = 0; x < length; x++)
{
System.out.print((char) buffer[x]);
}
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (SmbException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (fis != null)
{
try
{
fis.close();
}
catch (Exception ignore)
{
}
}
}
}
}
If the files are on a network-share you could use the net tool. With
runtime.exec("net use ...")
to open and close the share. I guess that should work