Puneet Purohit
Puneet Purohit

Reputation: 1291

redirect output to text file after user input

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.

Upvotes: 1

Views: 627

Answers (1)

fge
fge

Reputation: 121860

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.

Upvotes: 1

Related Questions