• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2016 Mockito contributors
3  * This program is made available under the terms of the MIT License.
4  */
5 package org.mockito.internal.util.io;
6 
7 import org.mockito.exceptions.base.MockitoException;
8 
9 import java.io.*;
10 import java.util.Collection;
11 import java.util.LinkedList;
12 import java.util.List;
13 
14 /**
15  * IO utils. A bit of reinventing the wheel but we don't want extra dependencies at this stage and we want to be java.
16  */
17 public class IOUtil {
18 
19     /**
20      * Writes text to file
21      */
writeText(String text, File output)22     public static void writeText(String text, File output) {
23         PrintWriter pw = null;
24         try {
25             pw = new PrintWriter(new FileWriter(output));
26             pw.write(text);
27         } catch (Exception e) {
28             throw new MockitoException("Problems writing text to file: " + output, e);
29         } finally {
30             close(pw);
31         }
32     }
33 
readLines(InputStream is)34     public static Collection<String> readLines(InputStream is) {
35         List<String> out = new LinkedList<String>();
36         BufferedReader r = new BufferedReader(new InputStreamReader(is));
37         String line;
38         try {
39             while((line = r.readLine()) != null) {
40                 out.add(line);
41             }
42         } catch (IOException e) {
43             throw new MockitoException("Problems reading from: " + is, e);
44         }
45         return out;
46     }
47 
48     /**
49      * Closes the target. Does nothing when target is null. Is silent.
50      *
51      * @param closeable the target, may be null
52      */
closeQuietly(Closeable closeable)53     public static void closeQuietly(Closeable closeable) {
54         try {
55             close(closeable);
56         } catch (MockitoException ignored) {
57             //ignore, for backwards compatibility
58         }
59     }
60 
61     /**
62      * Closes the target. Does nothing when target is null. Is not silent and exceptions are rethrown.
63      *
64      * @param closeable the target, may be null
65      */
close(Closeable closeable)66     public static void close(Closeable closeable) {
67         if (closeable != null) {
68             try {
69                 closeable.close();
70             } catch (IOException e) {
71                 throw new MockitoException("Problems closing stream: " + closeable, e);
72             }
73         }
74     }
75 }
76