1
2
3
4
5 package com.jcabi.xml;
6
7 import java.io.BufferedInputStream;
8 import java.io.File;
9 import java.io.FileNotFoundException;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.net.URI;
13 import java.net.URL;
14 import java.nio.charset.StandardCharsets;
15 import java.nio.file.Files;
16 import java.util.Scanner;
17 import lombok.EqualsAndHashCode;
18
19
20
21
22
23
24
25
26
27 @EqualsAndHashCode(of = "content")
28 final class TextResource {
29
30
31
32
33 private final transient String content;
34
35
36
37
38
39 private TextResource(final String text) {
40 this.content = text;
41 }
42
43
44
45
46
47
48
49
50 TextResource(final InputStream stream) {
51 this(TextResource.readAsString(stream));
52 }
53
54
55
56
57
58
59 TextResource(final File file) throws IOException {
60 this(
61 TextResource.readAsString(
62 new BufferedInputStream(Files.newInputStream(file.toPath()))
63 )
64 );
65 }
66
67
68
69
70
71
72 TextResource(final URL url) throws IOException {
73 this(TextResource.readAsString(url));
74 }
75
76
77
78
79
80
81 TextResource(final URI uri) throws IOException {
82 this(TextResource.readAsString(uri.toURL()));
83 }
84
85 @Override
86 public String toString() {
87 return this.content;
88 }
89
90
91
92
93
94
95 private static String readAsString(final InputStream stream) {
96 final String result;
97 try (Scanner scanner = new Scanner(
98 stream, StandardCharsets.UTF_8.name()
99 ).useDelimiter("\\A")) {
100 if (scanner.hasNext()) {
101 result = scanner.next();
102 } else {
103 result = "";
104 }
105 }
106 return result;
107 }
108
109
110
111
112
113
114
115 private static String readAsString(final URL url) throws IOException {
116 return TextResource.readAsString(
117 new BufferedInputStream(url.openStream())
118 );
119 }
120 }