0

I have the following problem. I have a txt file named password.txt on a unix server. I have a java class on the same server. I have to read the contents of the password.txt using this Java class. However, the Unix is running under root user and the root user does not have proper permissions to read this password.txt file directly. So, I have introduced a script and another java class which read the password.txt for me.

Basically, I call the script from the java class using Process and Runtime.exec(). The script invokes another java class which can read the password.txt file contents. But how do I get back the contents back to the java class which called the script? Someone suggested to assign the contents of the password.txt to an env variable and read that env variable in my java class. How do I implement this exactly. also, is this a good solution? Im very novice to UNIX and scripting. Pls help

Surya Chandra
  • 1,561
  • 5
  • 27
  • 42
  • may duplicate with http://stackoverflow.com/questions/1088941/java-reading-standard-output-from-an-external-program-using-inputstream – Summer_More_More_Tea Aug 09 '12 at 08:23
  • I think you have used one more unnecessary level of calling script (java -> script -> java), instead you should call script which read text for you and return contents to java class.`Process.getInputStream()` should do a trick for you. – Ved Aug 09 '12 at 08:31

2 Answers2

0

I confess I'm a little confused by your hierarchy of Java and scripts (I presume you can't read the file directly via FileReader). Perhaps you only need one Java class and one script (appropriately permissioned - like this or this ?).

But how do I get back the contents back to the java class which called the script?

You can't use an environment variable, since these are only available to a process and its children. If you change it in the child process you won't see the change in the parent.

I would get your reading class to write the data read to stdout (via a simple System.out.println()). You should be able to read the input stream from the process you've kicked off via Process.exec(). From the doc for Process.getInputStream():

Gets the input stream of the subprocess. The stream obtains data piped from the standard output stream of the process represented by this Process object.

There are a couple of gotchas wrt. reading data from spawned processes. See this answer for more details.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
0

You could let the script write the contents file to its standard output. The script could be perhaps just cat combined with su or sudo to get the appropriate permissions. Then you can read the data by calling getInputStream() on the Process object that you used to start the script.

Petr
  • 62,528
  • 13
  • 153
  • 317