InputStreamWriter implements DiskCache.Writer { @Override public boolean write(File file) { FileOutputStream stream = null; FileLock lock = null; try { stream = new FileOutputStream(file); lock = stream.getChannel().lock(); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int len = 0; while ((len = in.read(buffer)) != -1) { stream.write(buffer, 0, len); } return true; } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } finally { if (lock != null) { try { lock.release(); } catch (IOException e) { Log.w("InputStreamWriter", "Couldn't release lock"); } } IOUtils.close(stream); } } InputStreamWriter(InputStream in); @Override boolean write(File file);  }
@Test public void testWritesPng() throws Exception { InputStream is = new InputStream() { private int calls = 10; @Override public int read() throws IOException { if (calls < 20) return calls++; else return -1; } }; InputStreamWriter writer = new InputStreamWriter(is); File file = new File(getContext().getCacheDir(), "test_file"); boolean result = writer.write(file); Assert.assertTrue(result); file = new File(getContext().getCacheDir(), "test_file"); Assert.assertTrue(file.exists()); }
@Test public void testFailsGracefullyOnFileNotFound() throws Exception { InputStream is = new InputStream() { private int calls = 10; @Override public int read() throws IOException { if (calls < 20) return calls++; else return -1; } }; InputStreamWriter writer = new InputStreamWriter(is); File file = new File("http: boolean result = writer.write(file); Assert.assertFalse(result); }
@Test public void testFailsGracefullyOnIOException() throws Exception { InputStream is = new InputStream() { @Override public int read() throws IOException { throw new IOException("exception for test"); } }; InputStreamWriter writer = new InputStreamWriter(is); File file = new File(getContext().getCacheDir(), "test_file"); boolean result = writer.write(file); Assert.assertFalse(result); }