How to check if InputStream is Gzipped?

It’s not foolproof but it’s probably the easiest and doesn’t rely on any external data. Like all decent formats, GZip too begins with a magic number which can be quickly checked without reading the entire stream. public static InputStream decompressStream(InputStream input) { PushbackInputStream pb = new PushbackInputStream( input, 2 ); //we need a pushbackstream to … Read more

How to chain multiple different InputStreams into one InputStream

It’s right there in JDK! Quoting JavaDoc of SequenceInputStream: A SequenceInputStream represents the logical concatenation of other input streams. It starts out with an ordered collection of input streams and reads from the first one until end of file is reached, whereupon it reads from the second one, and so on, until end of file … Read more

What’s the fastest way to read from System.in in Java?

Is there any faster way of doing this in Java? Yes. Scanner is fairly slow (at least according to my experience). If you don’t need to validate the input, I suggest you just wrap the stream in a BufferedInputStream and use something like String.split / Integer.parseInt. A small comparison: Reading 17 megabytes (4233600 numbers) using … Read more

Why is using BufferedInputStream to read a file byte by byte faster than using FileInputStream?

In FileInputStream, the method read() reads a single byte. From the source code: /** * Reads a byte of data from this input stream. This method blocks * if no input is yet available. * * @return the next byte of data, or <code>-1</code> if the end of the * file is reached. * @exception … Read more

Closing Java InputStreams

The Properties class wraps the input stream in a LineReader to read the properties file. Since you provide the input stream, it’s your responsibility to close it. The second example is a better way to handle the stream by far, don’t rely on somebody else to close it for you. One improvement you could make … Read more

Connecting an input stream to an outputstream

Just because you use a buffer doesn’t mean the stream has to fill that buffer. In other words, this should be okay: public static void copyStream(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[1024]; // Adjust if you want int bytesRead; while ((bytesRead = input.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)