1

I have created a JNDI java program that gives different kind of output as user specification. For example user can run the program with different parameters as :

java MyProg -o row -u username -l uId1,uId2,....

here user can specify options as : -o : for output format(row basis/column basis) -u : connect to server with different user(then program will ask for password) -l : program will show output for given user id(s)

Now the thing is for every option I have define a default value(configuration) so its up to user if he want to change the configuration then he will specify the option. So user can call the program as:

java MyProg
java Myprog -o col
java MyProg -u username 
java MyProg -l uId1,uId2,...
java MyProg -l uId1,uId2,... -o col

and so on..

so whenever user use -u(for changing the username) then the program will ask the password after that it shows the result.

Now I want to provide a facility that user can redirect the console output to a text file but when I am trying "java MyProg > filename.txt" then its not working.

Please tell me how to redirect the output to a file.

8
  • Don't you print your results to stdout normally? Commented Jan 9, 2013 at 7:20
  • 1
    Its showing result to stdout but I want to provide facility to user that he can redirect the result to a file(optional). Commented Jan 9, 2013 at 7:24
  • Well, if shell redirections are not working, it seems like the results do not go to stdout (you say yourself that java MyProg > filename.txt does not redirect anything) Commented Jan 9, 2013 at 7:26
  • oh sorry..Its redirecting the output but when I write java MyProg -u username > filename.txt then its showing error Commented Jan 9, 2013 at 7:28
  • 1
    "java MyProg -u username > filename.txt" will be useless if you are expecting an input from the user. Try to implement writing the output to file as an option or default behavior and handle the same in the code as fge has given. Commented Jan 9, 2013 at 9:30

1 Answer 1

1

System.out is a PrintStream (which is why you can use such methods as println() etc on it).

What you can do is, if you see the option to redirect to a file, just create a new PrintStream to the destination file:

PrintStream stdout = System.out;

// outfile is a String
if (outfile != null)
    stdout = new PrintStream(outfile);

And use stdout instead of System.out to output results.

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

1 Comment

Instead System.setOut() can be used, so that System.out.println() also will be written to the specified file.

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.