1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package au.com.acegi.xmlformat;
19
20 import static java.nio.charset.StandardCharsets.UTF_8;
21
22 import static org.hamcrest.CoreMatchers.not;
23 import static org.hamcrest.CoreMatchers.nullValue;
24 import static org.hamcrest.MatcherAssert.assertThat;
25
26 import java.io.File;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.InputStreamReader;
30 import java.io.OutputStream;
31 import java.io.OutputStreamWriter;
32 import java.io.StringWriter;
33 import java.io.Writer;
34 import java.nio.file.Files;
35
36
37
38
39 final class TestUtil {
40
41 private TestUtil() {
42 }
43
44 static String fileToString(final File in) {
45 try (InputStream is = Files.newInputStream(in.toPath())) {
46 return streamToString(is);
47 } catch (final IOException ex) {
48 throw new IllegalStateException(ex);
49 }
50 }
51
52 static InputStream getResource(final String resource) {
53 final InputStream in = FormatUtilTest.class.getResourceAsStream(resource);
54 assertThat(resource + " not found", in, not(nullValue()));
55 return in;
56 }
57
58 static String streamToString(final InputStream in) {
59 final StringWriter sw = new StringWriter();
60 final InputStreamReader reader = new InputStreamReader(in, UTF_8);
61 final char[] buffer = new char[4_096];
62 int n;
63 try {
64 while (-1 != (n = reader.read(buffer))) {
65 sw.write(buffer, 0, n);
66 }
67 } catch (final IOException ex) {
68 throw new IllegalStateException(ex);
69 }
70 return sw.toString();
71 }
72
73 static void stringToFile(final String msg, final File out) {
74 try (OutputStream fos = Files.newOutputStream(out.toPath());
75 Writer writer = new OutputStreamWriter(fos, UTF_8)) {
76 writer.append(msg);
77 } catch (final IOException ex) {
78 throw new IllegalStateException(ex);
79 }
80 }
81
82 }