Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

I/O question  RSS feed

 
Eric Fletcher
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greetings all,
Here is my situation:
I need to read an input stream from a servlet, make some determinations about the validity of the data, then write the data both to a local file on the server and simoultaneously send it back to the browser as well.
Any suggestions for the best way to do this? My first pass just piped the response in via an InputStream, then directly back out via an OutputStream to the browser and via a FileOutputStream to the file. This works quickly but has two negatives:
1) I can't check the data
2) The data is written to the file in Unicode(instead of ASCII) and the formatting looks awful.
I was considering using a BufferedReader to convert the Stream to a String, validate the portion of the String I need to validate, then writing the String out to both the browser and the file using a PrintWriter and a FileWriter, but it seemed like a lot of work to accomplish this.
Any suggestions would be greatly appreciated.
Thanks,
Eric
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was considering using a BufferedReader to convert the Stream to a String, validate the portion of the String I need to validate, then writing the String out to both the browser and the file using a PrintWriter and a FileWriter, but it seemed like a lot of work to accomplish this.
You're pretty close. And it's not really that much work - the IO classes are designed to be put together in various combinations depending on what you want to do. The piece that you seem to be missing is that in order to convert an InputStream into Unicode characters, you need a Reader. Try this:

Writing to the file is a bit simpler, because a FileWriter already does the work of combining a FileOutputStream with an OutputStreamWriter (using your platform default encoding). However writing a response through the servlet back to the user is basically the reverse of the above process, with Writers and OutputStreams instead of Readers and InputStreams.
 
Eric Fletcher
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jim, I'll give that a try.
I appreciate the reply!
Eric
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!