1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.imaging.bytesource;
18
19 import java.io.File;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.nio.file.Path;
23 import java.util.Objects;
24
25 import org.apache.commons.imaging.common.BinaryFunctions;
26 import org.apache.commons.io.IOUtils;
27 import org.apache.commons.io.build.AbstractOrigin;
28 import org.apache.commons.io.build.AbstractOrigin.ByteArrayOrigin;
29 import org.apache.commons.io.build.AbstractOrigin.FileOrigin;
30 import org.apache.commons.io.build.AbstractOrigin.PathOrigin;
31
32 public class ByteSource {
33
34 public static ByteSource array(final byte[] array) {
35 return new ByteSource(new ByteArrayOrigin(array), null);
36 }
37
38 public static ByteSource array(final byte[] array, final String name) {
39 return new ByteSource(new ByteArrayOrigin(array), name);
40 }
41
42 public static ByteSource file(final File file) {
43 return new ByteSource(new FileOrigin(file), file.getName());
44 }
45
46 public static final InputStream getInputStream(final ByteSource byteSource, final long skip) throws IOException {
47 InputStream is = null;
48 boolean succeeded = false;
49 try {
50 is = byteSource.getInputStream();
51 BinaryFunctions.skipBytes(is, skip);
52 succeeded = true;
53 } finally {
54 if (!succeeded) {
55 IOUtils.close(is);
56 }
57 }
58 return is;
59 }
60
61 public static ByteSource inputStream(final InputStream is, final String name) throws IOException {
62 return new InputStreamByteSource(is, name);
63 }
64
65 public static ByteSource path(final Path file) {
66 return new ByteSource(new PathOrigin(file), Objects.toString(file.getFileName(), null));
67 }
68
69 private final String fileName;
70 private final AbstractOrigin<?, ?> origin;
71
72 ByteSource(final AbstractOrigin<?, ?> origin, final String fileName) {
73 this.origin = Objects.requireNonNull(origin, "origin");
74 this.fileName = fileName;
75 }
76
77 public byte[] getByteArray(final long position, final int length) throws IOException {
78 return origin.getByteArray(position, length);
79 }
80
81 public final String getFileName() {
82 return fileName;
83 }
84
85 public InputStream getInputStream() throws IOException {
86 return origin.getInputStream();
87 }
88
89
90
91
92
93
94
95 public long size() throws IOException {
96 return origin.size();
97 }
98
99 @Override
100 public String toString() {
101 return getClass().getSimpleName() + "[" + getFileName() + "]";
102 }
103
104 }