Java make a copy of a reader - java

I have a BufferedReader looping through a file. When I hit a specific case, I would like to continue looping using a different instance of the reader but starting at this point.
Any ideas for a recommended solution? Create a separate reader, use the mark function, etc.?

While waiting for your answer to my comment, I'm stuck with making assumptions.
If it's the linewise input you value, you may be as pleasantly surprised as I was to discover that RandomAccessFile now (since 1.4 or 1.5) supports the readLine method. Of course RandomAccessFile gives you fine-grained control over position.
If you want buffered IO, you may consider wrapping a reader around a CharacterBuffer or maybe a ByteBuffer wrapped around a file mapped using the nio API. This gives you the ability to treat a file as memory, with fine control of the read pointer. And because the data is all in memory, buffering is included free of charge.

Have you looked at BufferedReader's mark method? Used in conjunction with reset it might meet your needs.

If you keep track of how many characters you've read so far, you can create a new BufferedReader and use skip.
As Noel has pointed out, you would need to avoid using BufferedReader.readLine(), since readLine() will discard newlines and make your character count inaccurate. You probably shouldn't count on readLine() never getting called if anyone else will ever have to maintain your code.
If you do decide to use skip, you should write your own buffered Reader which will give you an offset counting the newlines.

Related

What are some real uses cases for the methods skip and reset in BufferedReader?

I'm trying to find out, what are the methods mark() and reset() of BufferedReader really useful for?
I understand what they are doing, but for going back and forth in some text I never used them - usually I solve this problem by reading either a sequence of chars or the whole line in an array or StringBuilder and go back and forth through it.
I believe there must be some reason why these methods are present in the BufferedReader and other Reader implementations supporting it but I'm unable to make an assumption why.
Does the usage of mark() & reset provide some benefit compared to reading the data in our own array and navigating through it?
I've searched through the codebase of one of my large projects I'm working on (mainly Java backend using Spring Boot), with lots of dependencies on the classpath and the only thing for which the mark & reset methods were used (in only very few libraries) was skipping an optional BOM character at the beginning of a text file. And even for this simple use case, I find it a bit contrived to do it that way.
Also, I was searching for other tutorials and on Stackoverflow (e.g. What are mark and reset in BufferedReader?) and couldn't find any explanation why to actually solve these kinds of problems using mark & reset. All code examples only explain what the methods are doing on "hello world" examples (jumping from one position in the stream back to a previous position for no particular reason). Nowhere I could find any explanation why someone should actually use it among other ways which sound more elegant and aren't really of worse performance.
I haven't used them myself, but a case that springs to mind is where you want to copy the data into a structure that needs to be sized correctly.
When reading streams and copying data into a target data structure (perhaps after parsing it), you always have the problem that you don't know how big to make your target in advance. The mark/rewind feature lets you mark, read the stream, parse it quickly to calculate the size, reset, allocate the memory, and then re-parse copying the data this time. There are of course other ways of doing it (e.g., using your own dynamic buffer), but if your code is already centered around the Reader concept then mark/reset lets you stay with that.
That said, even BufferedReader's own readLine method doesn't use this technique (it creates a StringBuffer internally).

why java has no StringBufferOutputStream

So if there is a java.io.StringBufferInputStream, you would think that there would be a StringBufferOutputStream.
Any ideas as to why there isn't??
Likewise,there is also a SequenceInputStream but no SequenceOutputStream.
My guess is that someone never got around to making a StringBufferOutputStream in Java 1.0 since the product was somewhat "rushed to market." By the time Java 1.1 rolled around and people actually understood that readers and writers were for characters, and inputstreams and outputstreams were for bytes, the whole concept of using streams for strings was realized to be wrong, so the StringBufferInputStream was rightly deprecated, with no chance ever of a partner coming along.
A SequenceInputStream is a nice way to read from a bunch of streams all concatenated together, but it doesn't make much sense to write a single stream to multiple streams. Well, I suppose you could make sense of this if you wanted to write a large stream into multiple partitions (reminds me of Hadoop here). It's just not common enough to be in a standard library. A complication here would be that you would need to specify the size of each output partition and would really only make sense for files (which can have names with increasing suffixes, perhaps), and so would not generalize into arbitrary output streams in a nice manner.
StringBufferInputStream is deprecated, because bytes and characters are not the same thing. The correct classes to use for this are StringReader and StringWriter.
If you think about it, there is no way to make a SequenceOutputStream work. SequenceInputStream reads from the first stream until it is exhausted, then reads from the next stream. Since an OutputStream is never exhausted (unless, say, it happens to be connected to a socket whose peer closes the connection), how would a SequenceOutputStream class know when to move on to the next stream?
StringBufferInputStream has long been depreciated.
Use StringReader and StringWriter.

Scanner vs InputStreamReader

Does anyone happen to know if there is any difference with regards to performance between the two methods of reading input file below?
Thanks.
1) Reading a file with Scanner and File
Scanner input = new Scanner(new File("foo.txt"));
2) Reading a file with InputStreamReader and FileInputStream
InputStreamReader input = new InputStreamReader(new FileInputStream("foo.txt"));
The first point is that neither of those code samples read a file. This may sound fatuous or incorrect, but it is true. What they actually do is open a file for reading. And in terms of what they actually do, there's probably not a huge difference in their respective efficiency.
When it comes to actually reading the file, the best approach to use will depend on what the file contains, what form the data has to be in for your in-memory algorithms, etc. This will determine whether it is better to use Scanner or a raw Reader, from a performance perspective and more importantly from the perspective of making your code reliable and maintainable.
Finally, the chances are that this won't make a significant difference to the overall performance of your code. What I'm saying is that you are optimizing your application prematurely. You are better of ignoring performance for now and choosing the version that will make the rest of your code simpler. When the application is working, profile it with some representative input data. The profiling will tell you the time is spent reading the file, in absolute terms, and relative to the rest of the application. This will tell you whether it is worth the effort to try to optimize the file reading.
The only bit of performance advice I'd give is that character by character reading from an unbuffered input stream or reader is inefficient. If the file needs to be read that way, you should add a BufferedReader to the stack.
In terms of performance, Scanner is definitely the slower one, at least from my experience. It's made for parsing, not reading huge blocks of data. InputStreamReader, with a large enough buffer, can perform on par with BufferedReader, which I remember to be a few times faster than Scanner for reading from a dictionary list. Here's a comparison between BufferedReader and InputStreamReader. Remember that BufferedReader is a few times faster than Scanner.
A difference, and the principal, I guess, is that with the BufferedReader/InputStreamReader you can read the whole document character by character if you want. With the scanner, this is not possible. It means that with InputStreamReader you can have more control over the content of the document. ;)

Java: Most efficient way to read from inputStream and write to an outputStream (plus a few modifications)

I am reading from an InputStream.
and writing what I read into an outputStream.
I also check a few things.
Like if I read an
& (ampersand)
I need to write
"& amp;"
My code works. But now I wonder if I have written the most efficient way (which I doubt).
I read byte by byte. (but this is because I need to do odd modifications)
Can somebody who's done this suggest the fastest way ?
Thanks
If you are using BufferedInputStream and BufferedOutputStream then it is hard to make it faster.
BTW if you are processing the input as characters as opposed to bytes, you should use readers/writers with BufferedReader and BufferedWriter.
The code should be reading/writing characters with Readers and Writers. For example, if its in the middle of a UTF-8 sequence, or it gets the second half of a UCS-2 character and it happens to read the equivalent byte value of an ampersand, then its going to damage the data that its attempting to copy. Code usually lives longer than you would expect it to, and somebody might try to pick it up later and use it in a situation where this could really matter.
As far as being faster or slower, using a BufferedReader will probably help the most. If you're writing to the file system, a BufferedWriter won't make much of a difference, because the operating system will buffer writes for you and it does a good job. If you're writing to a StringWriter, then buffering will make no difference (may even make it slower), but otherwise buffering your writes ought to help.
You could rewrite it to process arrays; and that might make it faster. You can still do that with arrays. You will have to write more complicated code to handle boundary conditions. That also needs to be a factor in the decision.
Measure, don't guess, and be wary of opinions from people who aren't informed of all the details. Ultimately, its up to you ot figure out if its fast enough for this situation. There is no single answer, because all situations are different.
I would prefer to use BufferedReader for reading input and BufferedWriter for output. Using Regular Expressions for matching your input can make your code short and also improve your time complexity.

Buffered vs non buffered, which one to use?

I am sorry if this is a duplicate but I was not able to find a definitive answer to what is the best practice for each type.
I would like to know what the appropriate conditions are that define when to use BufferedReader vs FileReader or BufferedInput/OutputStream vs FileInput/OutputStream? Is there a formula of sorts that will always tell you what is appropriate?
Should I just always used buffered?
Thanks
Use a buffer if the stream is going to have lots of small access. Use unbuffered if you are going to have relatively few, relatively large accesses.
The only time you should use unbuffered I/O is when the delay and aggregation imposed by buffering is inappropriate to your application.
" Is there a formula of sorts that will always tell you what is appropriate?"
If there was, it would already be in the libraries and would not be a design decision that you would have to make.
Since there's no pat answer, you have to make the design decision, you have to actually think about it.
Or, you can try both options and see which is "better" based on your unique problem and your unique criteria.
Most standard I/O libraries are buffered. That's a hint that most I/O benefits from buffering. But not all. Games, for instance, need unbuffered access to the game controls.
Keep in mind also that the BufferedReader provides you with a convenience readLine() method that allows you to read your content one line at a time.
I suggest you use Buffered* if this makes your application go faster, otherwise I wouldn't bother with it. i.e. try it with realistic data for see whether it helps.

Categories

Resources