0

I currently need to issue system commands from my java code but I stuck for a long time. I have been trying many forums and many code snippets but all either crash the app or seem to do nothing The last code I tried though works with "echo" but when I make "echo anystuff > y.txt", instead of creating a file called y.txt and write "anystuff" in the file, it just shows "anystuff > y.txt" in the textbox I created to see the output here is my method

public void ShellTest() throws IOException {
    // test 10
    String cmd="echo anystuff > y.txt";
    StringBuffer cmdOut = new StringBuffer();
    Process process;
    try{
        // issue the command here
        process = Runtime.getRuntime().exec(cmd);

        // prepare to get back the result and put it in the textbox "resText"
        DataOutputStream stdin = new DataOutputStream(process.getOutputStream());
        stdin.writeBytes(cmd);

        InputStreamReader r = new InputStreamReader(process.getInputStream());
        BufferedReader bufReader = new BufferedReader(r);
        char[] buf = new char[4096];
        int nRead = 0;
        while ((nRead = bufReader.read(buf)) > 0){
            cmdOut.append(buf,0,nRead);
        }
        bufReader.close();
        try {
            process.waitFor();
        } catch (InterruptedException e){
            e.printStackTrace();
        }
    } catch (IOException e){
        e.printStackTrace();
    }
    // check by the showing the output of the command in the textbox
    resText.setText(cmdOut); 
} 

BTW my phone is Google Pixel 2 XL
Any help would be appreciated!

2 Answers 2

1

Because the redirect isn't part of a system command. Its a feature of a (usually bash) shell. To get it to work, you'd need to run a shell then feed the command as an input to the shell. Running it as a command alone will get it all interpreted as arguments to the command echo.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply, but I have a question if the problem is only in the redirection (which I understood it is redirecting the output to the file y.txt "> y.txt") so why ls command is not working and I got nothing in the txt window. From my many tests it looks like for me that only echo is working (actually partially working). Plz correct me if I am wrong and guide me with the piece of the code that should be replaced and with what exactly. In other words, how can I run the shell first and then issue the command. Thanks
0

Chainfire the company who introduced SuperUser and SuperSU made a great library to handle all these stuffs . Install the library and it just works!

Layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_gravity="center"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textAlignment="center"
        android:text="Shell Executer" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/input_text"
        android:hint="Example - ls" />
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/execute_button"
        android:text="Execute" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/clear_button"
        android:text="Clear" />

    <TextView
        android:id="@+id/output_text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:textAlignment="textStart" />

</LinearLayout >

Java File

    public class MainActivity extends AppCompatActivity {

    Button execute, clear;
    EditText inputCommand;
    TextView outputResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        execute = findViewById(R.id.execute_button);
        clear = findViewById(R.id.clear_button);

        inputCommand = findViewById(R.id.input_text);
        outputResult = findViewById(R.id.output_text);
        outputResult.setMovementMethod(new ScrollingMovementMethod());

        execute.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                CommandResult result = Shell.SH.run(inputCommand.getText().toString());
                outputResult.append("$ " + inputCommand.getText().toString() + "\n" +
                        "> " + result.toString() + "\n");
            }
        });

        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                outputResult.setText("");
            }
        });
    }

}

Result: Image result

Library Link & how to use: https://github.com/jrummyapps/android-shell

Working test project: https://github.com/waleedhammam/Android-Shell

1 Comment

Thanks Hammam, this really works like charm. Just few quick notes: for whom who will use Hammam's code, first clear the project from the build menu in Android SDK. Some commands may need root access so be sure that either your emulator or phone is rooted first (search google for that if you do not know how to get root access to any of them). Finally if you gonna use the library in your code make sure to make sync after pasting "compile 'com.jrummyapps:android-shell:1.0.1'" in your build.gradle in the "dependencies" section. Thanks again Hammam.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.