News for hackers. Stuff that matters.
Re:Why I like Java by dlubarov on Tuesday March 25, 2014 @02:21AM (#7464203)
> Finally, do you think maybe you might need to worry about buffering of System.out's stream?

print() won't flush to the console unless you pass '\n' and auto-flushing is on. It will flush its internal buffer, but that's okay! The default System.out uses a BufferedOutputStream anyway:

    FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
    ...
    new PrintStream(new BufferedOutputStream(fdOut, 128), true)
So using print() instead of write() shouldn't cause any extra system calls, although there many be a small CPU cost.

Obvious, right? Don't you love java.io? :)

Re:Why I like Java by cbsmith on Tuesday March 25, 2014 @02:25AM (#7464214)
> The default System.out uses a BufferedOutputStream anyway

Yes, which is the _problem_, not the _solution_.

To clarify: the problem isn't that the code makes too many syscalls.

Re:Why I like Java by dlubarov on Tuesday March 25, 2014 @02:59AM (#7464323)
So what are you saying is the problem then? That writing to the BufferedOutputStream for each character is CPU-inefficient and he should be doing this?

    public static void main(String[] args) throws IOException {
        byte[] buffer = new byte[1 << 12];
        for (;;) {
            int nRead = System.in.read(buffer);
            if (nRead == -1) return;
            System.out.write(buffer, 0, nRead);
        }
    }
If so, fair enough, but it's reasonable to go with the simpler solution if you're not given any particular performance requirements.
Re:Why I like Java by cbsmith on Tuesday March 25, 2014 @03:09AM (#7464348)
No, I'm saying you are already using a BufferedInputStream and a BufferedOutputStream. That is the problem: you aren't guaranteeing your output matches your input.

Try doing this:

    dd if=/dev/random of=test_file bs=4000 count=100
    java YourClass < test_file > test_output
    diff test_file test_output
Re:Why I like Java by cbsmith on Tuesday March 25, 2014 @03:53AM (#7464466)
Here's the simpler, likely slower, but nonetheless actually correct solution: https://gist.github.com/cbsmith/9755809
Re:Why I like Java by dlubarov on Tuesday March 25, 2014 @11:40AM (#7466485)
Oh, gotcha. The code above with "byte[] buffer" also works since write(byte[], int, int) flushes.