I used the following code to run an exe I load through my code.
private static String filelocation = "";
.
load_exe.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
JFileChooser file_Choose = new JFileChooser();
file_Choose.showOpenDialog(frame);
JavaSamp.filelocation = file_Choose.getCurrentDirectory()
.toString()
+ "\\" + file_Choose.getSelectedFile().getName();
System.out.println("FileLocation" + JavaSamp.filelocation);
} catch (Exception expobj) {
// TODO Auto-generated catch block
}
Runtime rt = Runtime.getRuntime();
try {
System.out.println("File Run Location" + JavaSamp.filelocation);
proc = rt.exec(JavaSamp.filelocation);
} catch (IOException e4) {
e4.printStackTrace();
} catch (Exception e2) {
}
}
});
My problem is, the above execution of the JavaSamp.filelocation, should have to done many times. First time only I load the exe. Next time I wont. I need to store the exe in a string to run for the successive times.
Any suggestion pls
If you want remember the used file just initialize the filelocation with null and test for it. BTW: Storing it as File makes more sense and your way of constructing the absolute path is a bit intricate - compared to just calling getAbsolutePath()
private static File filelocation = null;
private static void test() {
load_exe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Check if file-name to execute has already been set
if (filelocation != null) {
try {
JFileChooser file_Choose = new JFileChooser();
file_Choose.showOpenDialog(frame);
JavaSamp.filelocation = file_Choose.getSelectedFile();
System.out.println("FileLocation"
+ JavaSamp.filelocation.getAbsolutePath());
} catch (Exception expobj) {
}
}
Runtime rt = Runtime.getRuntime();
try {
System.out.println("File Run Location"
+ JavaSamp.filelocation.getAbsolutePath());
Process proc = rt.exec(JavaSamp.filelocation
.getAbsolutePath());
} catch (IOException e4) {
e4.printStackTrace();
}
}
};
}
Related
I am writing an application that searches for Java files in a given directory and its subdirectories and writes all the strings from those files in reverse order to a new folder. Each directory and file is handled in a separate thread.
At the moment my program works correctly, but I want to change its behavior.
Right now, the program overwrites the files correctly and outputs the number of overwritten files to the console at the end. I want my program to just overwrite the files and display the line "All files overwritten" at the end. But I don't quite understand how I can change my code and replace Future (I think that's my problem). Here is part of the code from the Main class:
ExecutorService pool = Executors.newCachedThreadPool();
ReverseWritter reverseWritter = new ReverseWritter(dirToSearch, dirToStorePath + "//" + dirToStoreName, pool);
Future<Integer> res = pool.submit(reverseWritter);
try {
System.out.println(res.get() + " files reversed");
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
pool.shutdown();
Here's the method that overwrites the file:
public boolean reverseWrite(File file) {
if (file.isFile() && file.toString().endsWith(".java")) {
String whereTo = dirToStorePathName + "\\" + file.getName().substring(0, file.getName().indexOf(".java")) + "Reversed" + ".java";
try ( Scanner myReader = new Scanner(file); FileWriter myWriter = new FileWriter(whereTo);) {
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
myWriter.write(new StringBuffer(data).reverse().toString());
myWriter.write(System.getProperty("line.separator"));
}
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
return false;
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
return false;
}
}
return true;
}
And this is the call method (my class implements the Callable interface):
#Override
public Integer call() {
int count = 0;
try {
File[] files = dirToSearch.listFiles();
ArrayList<Future<Integer>> result = new ArrayList<>();
for (File f : files) {
if (f.isDirectory()) {
ReverseWritter reverseWritter = new ReverseWritter(f, dirToStorePathName, pool);
Future<Integer> rez = pool.submit(reverseWritter);
result.add(rez);
} else if (reverseWrite(f)) {
count++;
}
for (Future<Integer> rez : result) {
count += rez.get();
}
}
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
return count;
}
You just need to change the class to implement Callable<Void> and remove the operations which do the counting. Change the return type of call from Integer to Void.
public class ReverseWriterCallable implements Callable<Void> {
#Override
public Void call() throws Exception {
//do stuff
//don't do the counting operations
//when return type is Void you can only return null
return null;
}
}
Or implement Runnable and submit it to the executor service.
public class ReverseWriterRunnable implements Runnable {
#Override
public void run() {
//do stuff
//don't do the counting operations
}
}
Then just don't care about the result of the Future:
try {
res.get();
System.out.println("All files reversed");
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
pool.shutdown();
i want to copy directories from the the place where my .jar files exist?
here are what i tried.. but i always get /home/user/
how can i copy files from where my .jar program exist?
private void copy_dir() {
//Path sourceParentFolder = Paths.get(System.getProperty("user.dir") + "/Project/");
// Path sourceParentFolder = Paths.get(Paths.get(".").toAbsolutePath().normalize().toString());
Path destinationParentFolder = Paths.get(System.getProperty("user.home"));
try {
Stream<Path> allFilesPathStream = Files.walk(sourceParentFolder);
Consumer<? super Path> action = new Consumer<Path>() {
#Override
public void accept(Path t) {
try {
String destinationPath = t.toString().replaceAll(sourceParentFolder.toString(), destinationParentFolder.toString());
Files.copy(t, Paths.get(destinationPath));
} catch (FileAlreadyExistsException e) {
//TODO do acc to business needs
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
allFilesPathStream.forEach(action);
} catch (FileAlreadyExistsException e) {
//file already exists and unable to copy
} catch (IOException e) {
//permission issue
e.printStackTrace();
}
}
Try
Path destinationParentFolder = Paths.get(System.getProperty("user.dir"));
"user.dir" gets the absolute path from where your application was initialized.
"user.home" gets the user's home directory.
I have a JavaFX app where there is an editor. In the editor, the user will be able to write java code and I have a button to compile this code and run the main method. For example the editor will contain this code:
public class Test {
public static void main(String[] args) {
System.out.println("hello");
}
}
The button on click, will run this code:
runButton.setOnAction(e -> {
compiler.set(editor.getText());
try {
compiler.createFile();
} catch (IOException e1) {
e1.printStackTrace();
}
compiler.compile();
compiler.run();
});
In the compiler class, there is the following implementation:
public class CodeCompiler {
public String className;
public String code;
public void set(String code) {
try {
this.className = code.substring(code.indexOf(" class ") + 6, code.indexOf(" {")).trim();
} catch(StringIndexOutOfBoundsException e) {
}
this.code = code;
}
public void createFile() throws IOException {
PrintWriter pw = new PrintWriter("speech2code/src/main/java/" + className + ".java");
pw.close();
FileWriter writer = new FileWriter("speech2code/src/main/java/" + className + ".java", true);
writer.write(code);
writer.flush();
writer.close();
}
public void compile() {
File file = new File("speech2code/src/main/java/" + className + ".java");
File classFile = new File("speech2code/src/main/java/" + className + ".class");
classFile.delete(); // delete class file f it exists
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, file.getPath());
}
public void run() {
Class<?> cls = null;
try {
cls = Class.forName(className);
System.out.println(cls == null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method meth = null;
try {
meth = cls.getMethod("main", String[].class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
String[] params = null;
try {
meth.invoke(null, (Object) params);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
Now the code above successfully creates the java file, class file and runs correctly the first time. Now when I change the editor code to print something else, it outputs the result of the first time the code was running. So, in this case, it will still print 'hello' instead of whatever it's current value.
Any problem what might be wrong?
Thanks!
You need to create a new classloader for the new class. The class does not get reloaded just because you compiled it.
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] {classFile});
Then you can ask this loader for the class:
Class<?> cls = Class.forName(className, true, classLoader);
Recently I added "adb devices" in the nano ./bash_profile so that I can run it from any directory.
I used one java application to run
public static void main(String [] args) {
executeCmd("adb devices");
}
private static void executeCmd(String string) {
InputStream pipedOut = null;
try {
Process aProcess = Runtime.getRuntime().exec(string);
// These two thread shall stop by themself when the process end
Thread pipeThread = new Thread(new StreamGobber(aProcess.getInputStream()));
Thread errorThread = new Thread(new StreamGobber(aProcess.getErrorStream()));
pipeThread.start();
errorThread.start();
aProcess.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
class StreamGobber implements Runnable {
private InputStream Pipe;
public StreamGobber(InputStream pipe) {
if(pipe == null) {
throw new NullPointerException("bad pipe");
}
Pipe = pipe;
}
public void run() {
try {
byte buffer[] = new byte[2048];
int read = Pipe.read(buffer);
while(read >= 0) {
System.out.write(buffer, 0, read);
read = Pipe.read(buffer);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(Pipe != null) {
try {
Pipe.close();
} catch (IOException e) {
}
}
}
when I run any other commands such as "ls" it's working fine!!
I'm using mac ..
thanks :)
Maybe global path problem on mac. You can try run with absolute adb program path as command.
I am trying to use java to open an exe file. I'm not sure which program I want to open so I am using Skype as an example. When I try to do it, it gives me errors.
try {
Process p = Runtime.getRuntime().exec("C:\\Program Files (x86)\\Skype\\Phone\\Skype");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
error:
Cannot run program "C:\Program": CreateProcess error=2, The system cannot find the file specified
Try this:
String path = "/path/to/my_app.exe";
File file = new File(path);
if (! file.exists()) {
throw new IllegalArgumentException("The file " + path + " does not exist");
}
Process p = Runtime.getRuntime().exec(file.getAbsolutePath());
You have to use a string array, change to
try {
Process p = Runtime.getRuntime().exec(new String[] {"C:\\Program Files (x86)\\Notepad++\\notepad++.exe"});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You are on windows so you have to include the extension .exe
try {
Process p = Runtime.getRuntime().exec("C:/Program Files (x86)/Skype/Phone/Skype.exe");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Maybe use File.separator instead of '\'
I tried this and it works fine, it's taken from your example. Pay attention to the double \\
public static void main(String[] args) {
try {
Process p;
p = Runtime.getRuntime().exec("C:\\Program Files\\Java\\jdk1.8.0_05\\bin\\Jconsole.exe");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}