2

I have a Selenium tests written in Java which runs as Jenkins job. I need to have chmod set up to 777 cause otherwise it throws me an error. But I would like to set up chmod properly to somenthing like 775. The problem is that I dont know who is the user which runs the Java tests. I have this code in Java

System.out.println(Runtime.getRuntime().exec("whoami"));

which returns this: Process[pid=2116487, exitValue=0] Can somebody tell me please what is it? Obviously it is not a user I can set up as owner or as a group of the repository.

Thanks.

Čamo
  • 3,863
  • 13
  • 62
  • 114
  • 1
    Does this answer your question? [Get login username in java](https://stackoverflow.com/questions/797549/get-login-username-in-java) – Thomas Jun 22 '21 at 08:18
  • https://stackoverflow.com/questions/473446/java-current-machine-name-and-logged-in-user check this – YaDav MaNish Jun 22 '21 at 10:48

3 Answers3

2

To get the output of the process, you need to attach the InputStream of to the normal output of the subprocess. Then, you can read from it by creating a BufferedReader. To get the first line of the output of the process (on stdout) you can use this code:

Process proc = Runtime.getRuntime().exec("whoami");
BufferedReader stdin = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String username = stdin.readLine();
System.out.println(username);

You can also get the InputStream of the error output of the subprocess (stderr) with proc.getErrorStream() if this should be necessary.


However, there is a better way if you want to get the username of the user executing the VM:

String username = System.getProperty("user.name");
System.out.println(username);
Matt
  • 12,848
  • 2
  • 31
  • 53
1

You are not getting the output of the process "whoami", but the process properties. Try

System.out.println(new Printstream(Runtime.getRuntime().exec("whoami").getOutputStream()));
Mathias
  • 282
  • 1
  • 16
0

Do you want this?

System.getProperty("user.name")
James Mudd
  • 1,816
  • 1
  • 20
  • 25