Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

commandline output to file  RSS feed

 
Matthew Joseph
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to make a method that takes in a cmd command (nslookup, systeminfo, etc), and outputs the response to a text file. I have tried a dozen different ways with no success. below is my most current failure.
Could anyone tell me where I am going wrong? It succeeds when i run it, but nothing shows up in the text file.

 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's probably an exception - about which you'll never know because you have an empty catch block (something you should never do with I/O code).

I think a more natural way of doing this would be to print all output to System.out, and then pipe the output into a file, like "java WhatEver > ping.txt". That way you don't have to deal with file I/O in the code.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also you appear not to be “ emptying” both Streams from the Process. You can get all sorts of errors if you don't do that.
You can simply collect everything which comes out of the input Stream into a List<String> and inspect it later (actually, both Streams can be directed to a List). Leave the file writing until you have got the rest of the program working correctly. If you can simply display everything on screen, then you are winning.
I do not like methods like read(); you can get the whole line as a String from other methods. And there will be no risk of your ever overflowing the bounds of the array.

And finally, never go anywhere near Runtime.exec() until you have read about the ProcessBuilder class and the classic article which you can find by Googling “Michael Daconta when Runtime.exec() won't”.

Processes are too difficult for us beginners, so I am moving this discussion.
 
Matthew Joseph
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ulf, no empty catch blocks-noted.
Campbell, thank you for the advice on using the list. my command line method is kicking butt now.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now you have got the List, convert it to a field. Or make the method return an unmodifiable version of that List, which may be better.

Now you have got a reference to that List you can play with it and try writing it to your file.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!