javastringreader

Should I close a StringReader?


I use a StringReader to turn a string into something I can upload to an SFTP server (it takes a stream). Is there any point in closing that StringReader afterwards? As far as I can see in the source it just sets the string to null...

I could just do it, but since the close method is marked as throwing an IOException and all I have to wrap it in a try catch and the code just ends up looking a lot more horrible than it perhaps needs to be.


Solution

  • If you know you're dealing with a StringReader that you'll be throwing away, I don't see any reason to close it. I can't imagine any reason you'd be holding a reference to it after you'd close it, so there's no real benefit to the string being set to null for garbage collection. If you were creating a method that takes a Reader then it might make sense to close it since you don't know the underlying type.