How to convert OutputStream to InputStream?

There seem to be many links and other such stuff, but no actual code using pipes. The advantage of using java.io.PipedInputStream and java.io.PipedOutputStream is that there is no additional consumption of memory. ByteArrayOutputStream.toByteArray() returns a copy of the original buffer, so that means that whatever you have in memory, you now have two copies of … Read more

How can I read a text file in Android?

Try this : I assume your text file is on sd card //Find the directory for the SD Card using the API //*Don’t* hardcode “/sdcard” File sdcard = Environment.getExternalStorageDirectory(); //Get the text file File file = new File(sdcard,”file.txt”); //Read text from file StringBuilder text = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(file)); … Read more

Different ways of loading a file as an InputStream

There are subtle differences as to how the fileName you are passing is interpreted. Basically, you have 2 different methods: ClassLoader.getResourceAsStream() and Class.getResourceAsStream(). These two methods will locate the resource differently. In Class.getResourceAsStream(path), the path is interpreted as a path local to the package of the class you are calling it from. For example calling, … Read more

Is it possible to read from a InputStream with a timeout?

Using inputStream.available() It is always acceptable for System.in.available() to return 0. I’ve found the opposite – it always returns the best value for the number of bytes available. Javadoc for InputStream.available(): Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next … Read more

Creating a byte array from a stream

While Jon’s answer is correct, he is rewriting code that already exists in CopyTo. So for .Net 4 use Sandip’s solution, but for previous version of .Net use Jon’s answer. Sandip’s code would be improved by use of “using” as exceptions in CopyTo are, in many situations, quite likely and would leave the MemoryStream not … Read more