I am trying to use adb for working with the files in my device from a MAC PC.
One of my folders in my phone has a space in it, so I looked around and tried using escape i.e \ and also using quotes with as given below
import java.io.*;
public class TestModule {
public static void main(String[] args) throws IOException,InterruptedException {
String line = "null";
String cmd = "adb pull /storage/sdcard1/Android/data/files/test\\ Information/ /Users/sbc/Desktop";
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
while ((line=buf.readLine())!=null) {
System.out.println(line);
}
}
}
I ran the same command in terminal I can access the file but through java it gives me remote object does not exist error.
Any help is very much appreciated
I found a workaround for my problem, posting code below,
import java.io.*;
public class TestModule {
public static void main(String[] args) throws IOException,InterruptedException {
String line = "null";
String cmd = "adb pull /storage/sdcard1/Android/data/files /Users/sbc/Desktop";
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
while ((line=buf.readLine())!=null) {
System.out.println(line);
}
}
}
In place of accessing the folder with the space, I accessed it's parent folder
/storage/sdcard1/Android/data/files/test\ Information/<--current folder with space
/storage/sdcard1/Android/data/files<--Parent Folder.
Now adb downloads all the contents of "Parent Folder"
Related
I'm using this code to load a .java file and do the search:
public class FindClassName {
public static void main(String[] args) {
Logger logger = Logger.getLogger("MOJ.Logger");
try(Scanner scanner = new Scanner(new FileReader("./src/string/FindClassName.java"))){
String pattern = "class\\s*(\\w+)\\s*";
List<String> list = new LinkedList<>();
while(scanner.hasNext()){
String line = scanner.nextLine();
Matcher matcher = Pattern.compile(pattern).matcher(line);
while(matcher.find()){
list.add(matcher.group(1));
}
}
System.out.println(list);
}catch(IOException exception){
logger.info("Couldn't read file");
}
}
static class CHUJ{
}
}
it works but when I export this to executable .jar file then It can't load file to reader. I've read that I need to use:
FindClassName.class.getResource("FindClassName.java");
but this gives me NullPointerException. I tried many different approaches but still couldn't load that .java file to reader with getResource() or getResourcesAsStream().
I know there are tons of questions like that, but I couldn't find the solution.
EDIT
this is strange, this code now runs in executable jar(with resources included) but not within eclipse... why? is there a better way?
public class FindClassName {
public static void main(String[] args) throws FileNotFoundException {
Logger logger = Logger.getLogger("MOJ.Logger");
//String directory = "./src/string/FindClassName.java"; //to będzie działać w eclipsie, ale jak zrobisz z tego jar to wszystkie pliki .java zostaną skompilowane na .class
InputStream directory = FindClassName.class.getResourceAsStream("FindClassName.java");
try(Scanner scanner = new Scanner(new InputStreamReader(directory))){
String pattern = "class\\s*(\\w+)\\s*";
List<String> list = new LinkedList<>();
while(scanner.hasNext()){
String line = scanner.nextLine();
Matcher matcher = Pattern.compile(pattern).matcher(line);
while(matcher.find()){
list.add(matcher.group(1));
}
}
System.out.println(list);
}
}
static class CHUJ{
}
}
Problem:
When you create an excecutable JAR (Actually any jar) all the .java files are compiled and transformed into .class files that can be used then by the JVM.
Solution:
One solution is to include the source code directory as additinal resource directory (Not a normal usecase):
<build>
<resources>
<resource>
<directory>${project.build.sourceDirectory}</directory>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
See this link for more information or this video using Eclipse
Something like this should do it:
C:\>java -jar JarFileExample.jar
package com.mycompany.myproject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class JarFileExample {
public static void main(String[] args) throws Exception {
InputStream is = JarFileExample.class.getResourceAsStream("/com/mycompany/myproject/JarFileExample.java");
writeFileToConsole(is);
}
private static void writeFileToConsole(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
for(String str = reader.readLine(); str != null; str = reader.readLine()) {
System.out.println(str);
}
reader.close();
}
}
C:\>
The source code can easily be included in the jar file but depends on the tool you are using to create the jar. I used eclipse and basically the method described here: Eclipse: include source code while exporting as runnable jar
Mac OS here, but looking for a solution that is platform agnostic. Also please note, even though Consul is mentioned here, it is just arbitrary and the solution should have nothing to do with, nor require knowledge of, Consul.
When I open a shell and run consul -v (to determine if Consul is installed locally), I get the following STDOUT:
Consul v0.5.2
Consul Protocol: 2 (Understands back to: 1)
When I run the following code:
public class VerifyConsul {
public static void main(String[] args) {
PrintStream oldPS = System.out;
try {
Runtime runtime = Runtime.getRuntime();
Process proc;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream newPS = new PrintStream(baos);
System.setOut(newPS);
proc = runtime.exec(“consul -v”);
proc.waitFor();
String capturedOut = baos.toString();
if(capturedOut.isEmpty()) {
throw new IllegalArgumentException(“Consul not found.”);
}
} catch(Throwable t) {
System.out.println(t.getMessage());
System.setOut(oldPS);
}
}
}
I get the IllegalArgumentException stating that Consul [is] not found.
What is wrong with my code? Why isn’t it “hooking”/capturing STDOUT?
Use Process#getInputStream() to read STDOUT or Process#getErrorStream() to read STDERR
Here's an example (using java process and reading STDERR):
package so32589604;
import org.apache.commons.io.IOUtils;
public class App {
public static void main(String[] args) throws Exception {
final Runtime runtime = Runtime.getRuntime();
final Process proc = runtime.exec("java -version");
proc.waitFor();
// IOUtils from apache commons-io
final String capturedOut = IOUtils.toString(proc.getErrorStream());
System.out.println("output = " + capturedOut);
if(capturedOut.isEmpty()) {
throw new IllegalArgumentException("Java not found.");
}
}
}
I have a self-contained Java application packaged with the javapackager tool (version 8.0, Windows). How do I pass it system property values at application runtime (not at package time) on the command line?
The doc does not seem to address this.
I tried the standard Java way as in:
mypackagedapp.exe -Dmyprop=myvalue
but that does not appear to have an effect.
Here is a code that validates if an argument exists in the command line.
See if the next code can help you.
public static void main(final String[] args) throws Exception {
CommandLine line = validateArgs(args);
if (null == line) {
return;
}
}
private static CommandLine validateArgs(String[] args) {
Options flags = getArgs();
CommandLineParser parser = new BasicParser();
CommandLine line = null;
try {
// parse the command line arguments
line = parser.parse(flags, args);
if (line == null) {
return null;
}
} catch (ParseException exp) {
System.out.println(exp.getMessage());
}
return line;
}
static Options getArgs() {
Options flags = new Options();
Option dmyprop = OptionBuilder.withArgName("dmyprop")
.hasArg()
.withDescription("add description")
.create("Dmyprop");
flags.addOption(dmyprop);
return flags;
}
In order to get environment variable you need to use:
String env = System.getenv(option);
where option is your desired environment variable.
Hope it helped.
I know that I can run non GUI jar files from the command line. Is there any way that can do so by clicking or something and not writing the commands again and again.? Is there any software to do so. ( I am talking about a compiled jar and don't want to run from any ide)
public static final String TITLE = "CONSOLE title";
public static final String FILENAME = "myjar.jar";
public static void main(String[] args) throws InterruptedException, IOException {
if(args.length==0 || !args[args.length-1].equals("terminal")) {
String[] command;
if(System.getProperty("os.name").toLowerCase().contains("win")) {
command = new String[]{"cmd", "/c", "start \"title \\\""+TITLE+"\\\" & java -jar \\\""+new File(FILENAME).getAbsolutePath()+"\\\" terminal\""};
} else {
command =new String[]{"sh", "-c", "gnome-terminal -t \""+TITLE+"\" -x sh -c \"java -jar \\\""+new File(FILENAME).getAbsolutePath()+"\\\" terminal\""};
}
try {
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
} catch(Throwable t){
t.printStackTrace();
}
} else {
//THERE IS YOUR CONSOLE PROGRAM:
System.out.println("Hey! What's your name?");
String read = new BufferedReader(new InputStreamReader(System.in)).readLine();
System.out.println("Hey, "+read+"!");
Thread.sleep(10000);
}
}
You can run it with double clicking on .jar file. Don't forget about MANIFEST.MF! :) (working on linux, also!)
Example (I only double clicked on jar file):
The way intended by Java is that you call java -jar XXXX.jar on the jars you need. Drawback is that you can't specify a classpath so all classes should be there.
A cooler way to package an application is by using Java WebStart. With that the user installs the application jut by clicking on a web browser. Check here http://docs.oracle.com/javase/8/docs/technotes/guides/javaws/developersguide/contents.html
I'm trying to run a Java program from another Java application. Here is my code:
public class Main {
public static int Exec() throws IOException {
Process p = Runtime.getRuntime().exec("javac -d C:/Users/Dinara/Desktop/D/bin "
+ "C:/Users/Dinara/Desktop/D/src/test.java");
Process p1 = Runtime.getRuntime().exec("java -classpath C:/Users/Dinara/Desktop/D/bin test");
return 0;
}
public static void main(String[] args) throws IOException {
Exec();
}
}
javac works fine and creates test.class file in bin directory. However java -classpath C:/Users/Dinara/Desktop/D/bin test does not run the test.class file.
the content of the test.java:
import java.io.*;
class test {
public static void main(String args[]) {
try {
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
I suppose that something wrong with recognizing Java command. Could you please give me a sample code for fixing this problem or share idea? I'm using Netbeans to run Main class and the location of the application folder is C:\Users\Dinara\Main
Use
System.getProperty("java.home") + "/bin/java -classpath C:/Users/Dinara/Desktop/D/bin test"
instead of
"java -classpath C:/Users/Dinara/Desktop/D/bin test"
You need to supply the full path to the javac, exec won't use the ath to find it for you