Hot questions for Using Ubuntu in terminal

Question:

I'm working with a java library which needs two files 'library.jar' and 'library-extensions.jar'. Whenever I try to include both of them separated by a colon (e.g. -cp "library.jar:library-extensions.jar") and try to use auto-complete on the second jar file, it substitutes the first argument for the second one.

i.e.

I have something like this:

java -cp "library.jar:l

I press 'Tab' to auto-complete the second argument and it changes to:

java -cp "l

Is there anything I can do to enable proper auto-complete on additional arguments?

I'm using terminal on Ubuntu 14.04.


Answer:

You are using double quotes (") which is causing you problem.

Remove double quotes & auto-complete will work easily :)

Question:

import java.io.*;
import java.io.IOException;
import java.util.Scanner;

public class AutoStart{
    public static void main(String[] args){
        while(true){
            Runtime r = Runtime.getRuntime();
            try{
                Process p = r.exec("ps -ef >> services.txt");
                try{
                    p.waitFor();
                } catch(InterruptedException e){
                    e.getStackTrace();
                }   

                Scanner txtscan = new Scanner(new File("services.txt"));
                int running = 0; //0 means not running and 1 means running
                while(txtscan.hasNextLine()){
                    String str = txtscan.nextLine();
                    if(str.indexOf("red5") != -1){
                        running = 1;
                    }
                }

                if(running == 0){
                    //red5 is not running so start it now
                    //code to start it goes here
                }

                //at the end remove services.txt file
                //code to remove that file goes here.


            } catch(IOException e){
                e.getStackTrace();
            }

            try {
                Thread.sleep(1000);                 //1000 milliseconds is one second.
            } catch(InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

        }
    }
}

On line 10 I am trying to create a text file which contains list of all the running programs but my java program is not able to create it.

This program is not able to create services.txt file and I don't get any error at all so I am confused what's the problem. Can you help me figure out the problem? Thank you.


Answer:

This calls a subprocess without relying on any shell mechanism, catching the resulting standard output.

public static void main( String[] args ) throws Exception {
  try { 
    ProcessBuilder pb = new ProcessBuilder( "/bin/ps", "-ef" );
    Process process = pb.start();
    InputStream is = process.getInputStream();
    Reader rdr = new InputStreamReader( is );
    LineNumberReader lnr = new LineNumberReader(rdr);
    String line;
    while( (line = lnr.readLine()) != null ){
      if( line.contains( "skype" ) ){
        System.out.println( "skype is running" );
      }
    }
    process.waitFor();
  } catch( Exception e ){

  } catch( Error e ){

}

Question:


Answer:

You need to include your Test4 class file to the classpath.

Assuming your Test4.class file is located on /opt/Tests/Test4/src/test4 and the fully qualified name is test4.Test4 then you should do something like:

/opt/Tests/Test4/src> java -cp "/opt/glassfish5/glassfish/lib/*":"." test4.Test4

Note that the directory of the terminal is /opt/Tests/Test4/src and not /opt/Tests/Test4/src/test4

Hope this helps

Question:

I'm trying to run some pulseaudio operations with ProcessBuilder in Java, e.g. pacmd list-source-outputs on Ubuntu 18.04. When I run the code directly from Intellij it says No PulseAudio daemon running, or not running as session daemon. However, if I go to build/classes/java/main and execute java MyMainClass it works as expected.

I assume that it has something to with how the Intellij terminal is integrated. It doesn't seem to behave the same as the OS terminal (see image). Does anyone have more insights about the Intellij Terminal?

Process p = null;
try {
    p = new ProcessBuilder("pacmd", "list-source-outputs").start();

    printStream(p.getInputStream());
    printStream(p.getErrorStream());

    p.waitFor();
} catch (IOException | InterruptedException e) {
    e.printStackTrace();
}

Edit: My Terminal settings:


Answer:

The problem was with pulseaudio. What worked for me was to call

export PULSE_RUNTIME_PATH=/run/user/1000/pulse

before running any pulseaudio/pacmd/pacntl command. The export command doesn't seem to work from runtime. However, you can create a shell file and then execute your commands:

test.sh:

#!/bin/bash
export PULSE_RUNTIME_PATH=/run/user/1000/pulse
pacmd list-source-outputs

In Java:

Runtime.getRuntime().exec("sh test.sh");

Easier handling for dynamic calling:

test.sh:

#!/bin/bash
export PULSE_RUNTIME_PATH=/run/user/1000/pulse
$1

In Java:

Runtime.getRuntime().exec("sh test.sh \"pacmd list-source-outputs\"");

Here is the official answer from Jetbrains:

How do you launch IDE: from terminal via .sh script or from desktop launcher? make sure to try to launch it from terminal via .sh script.

Also try restarting the IDE after starting the pulseaudio or restart the pulseaudio daemon in IDE terminal. Try also these suggestions: https://bbs.archlinux.org/viewtopic.php?pid=1214072#p1214072 https://bbs.archlinux.org/viewtopic.php?pid=1214157#p1214157

Note that after changing the environment it might be needed to restart the IDE.

Question:


Answer:

I find Karol's response to be great, however another suggestion to show there are many ways to do this on Unix :)

Suppose your class is called JavaClass and arguments stored on .txt

xargs -a .txt java JavaClass

Has same effect than

java JavaClass $(cat .txt)

Question:

I am currently using a command called "curl" from Terminal in Ubuntu, tu upload my .RDF files to a Virtuoso RDF Store.

curl -T FILE URL -u USER:PASSWORD

I want to automatize these process, so that I create a Java function in eclipse. This code is not working.

String[] command = {"curl -T", FILENAME, URL, "-u", credentials.USERNAME+":"+credentials.PASSWORD};
Runtime.getRuntime().exec(command)

I have also tried with this one. The xterm appears, but it shows this error (even though the file is in the Path of the function):

*"/usr/bin/xterm. Can't execvp "curl" no such a directory or file"*


Runtime.getRuntime().exec("/usr/bin/xterm -e \"curl -T " + FILENAME  
                                                        + " " + URL + "-u " + credentials.USERNAME
                                                        + ":" + credentials.PASSWORD + "\"");

I would appreciate any help on the matter.

Thanks in advance


Answer:

I have had a hard time trying to get commands run using Runtime.exec() in the past. Anyways I have shifted to using ProcessBuilder as follows:

ProcessBuilder pbuilder = new ProcessBuilder("bash", "-c", <<your command as string>>);
        File err = new File("err.txt");
        try {
            pbuilder.redirectError(err);
            Process p = pbuilder.start();
            p.waitFor();      

        } catch (Exception e) 
        {
             //handle exceptions if any.
        }

The stderr line is optional, for debugging purposes. I am sure that it could be directly printed out to console, but havn't checked on it yet. Will update my answer, once I find more.

You can check out the documentation page here.

PS: Also check if you have the necessary permissions to carry out the desired task.

Question:

I've looked around and nothing has solved my problem.

I'm trying to launch a .class file within terminal while including another directory. This is how I'm doing it:

java -cp lib/*:bin/ org.package.file

However I keep getting an error essentially stating that I'm not including the lib directory.

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/collect/Lists

The file is bin/org/package/file and I need to include the entire lib directory.

I'm doing this in Terminal on an Ubuntu OS.


Answer:

You will need to specify individual libraries in the command line to specify the classpath rather than using wildcard like:

java -cp lib/a.jar:lib/b.jar:bin/ org.package.file

From the looks of it, you do have guava jar in your lib directory, so try to include all the jar's in your lib directory like above and that should resolve your issue.

Question:

So I have a Java-file e.g. example.java. I've then compiled it using javac (I then made a .class file in my directory, example.class).

I now want to run it using standard input with a .txt file in the ubuntu terminal. I remember it being fairly easily done with Python, but I'm not quite sure what to do with Java.

I want something along the lines of

dir$ java example indata.txt

That would pass my file indata.txt as standard input into my program.


Answer:

I managed to solve my problem - the way I did it was as follows (in the terminal, standing in the same directory as my .java, .class and .txt files;

java example < indata.txt

Question:

I want to run a command in Termninal(Ubuntu) using java program

After surfing in internet i found out way to execute commands using java

Following is the code to find ldd version in ubuntu

String[] command = { "ldd", "--version" };
            ProcessBuilder probuilder = new ProcessBuilder(command);
            Process process = probuilder.start();
            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            process.waitFor();

            // System.out.println(br.readLine());
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

In the above code i trying to find out "ldd verison" using java in ubuntu. which worked fine i am got ldd version.

But when i tried to find java version of my ubuntu in the same way. The code is returning nothing because br.readline is null. iwas abel to find out ldd vesion,why not java version?

Following is the code to find out java version in ubuntu using java

String[] command = { "java", "-version" };

    ProcessBuilder probuilder = new ProcessBuilder(command);
    Process process = probuilder.start();

    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    process.waitFor();

    // System.out.println(br.readLine());
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }

Some one please help me to find out how to find java version using java code in ubuntu.


Answer:

Unfortunately this is the way Java was implemented. It appears that Java's -version option gets printed through the stderr instead of the usual stdout

Reference: Why does 'java -version' go to stderr?

This phenomenon explains why your subprocess ran the command but seem everything is printed through the stderr channel it seems as thou it didn't failed executing the command but when you dump the error stream through process.getErrorStream() you see the version text instead.

You should be able to get the Java version number through the 'java.version' system property.

Example:

System.out.println( System.getProperty("java.version") );

Output:

1.8.0_51

You might be interested in the other Java related properties that you can print - like runtime and product build version etc.

See: http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html