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