| 131 | } |
| 132 | |
| 133 | public static void CopyPartially(String pathStr, OutputStream out, long offset, int length) throws IOException { |
| 134 | logger.info("CopyPartially begin, path: {}, offset: {}, length: {}", new Object[] {pathStr, offset, length}); |
| 135 | Configuration conf = new Configuration(); |
| 136 | Path path = new Path(pathStr); |
| 137 | |
| 138 | try(FileSystem fs = FileSystem.get(path.toUri(), conf)) { |
| 139 | logger.debug("begin exists, path: {}", pathStr); |
| 140 | if (!fs.exists(path)) { |
| 141 | logger.warn("CopyPartially File does not exist, path: {}", pathStr); |
| 142 | out.write(("File does not exist: " + pathStr).getBytes()); |
| 143 | return; |
| 144 | } |
| 145 | logger.debug("begin getFileStatus, path: {}", pathStr); |
| 146 | FileStatus stat = fs.getFileStatus(path); |
| 147 | if (stat.isDir()) { |
| 148 | logger.warn("CopyPartially Can not read directory, path: {}", pathStr); |
| 149 | out.write(("Can not read directory: " + pathStr).getBytes()); |
| 150 | return; |
| 151 | } |
| 152 | if (offset + length > stat.getLen()) { |
| 153 | logger.warn("CopyPartially Not enough data, path: {}", pathStr); |
| 154 | out.write(("Not enough data: " + pathStr).getBytes()); |
| 155 | return; |
| 156 | } |
| 157 | |
| 158 | logger.debug("begin read, path: {}", pathStr); |
| 159 | try(FSDataInputStream in = fs.open(path)) { |
| 160 | int bufferSize = 48 * 1024; |
| 161 | byte[] buffer = new byte[bufferSize]; |
| 162 | int readSize = 0; |
| 163 | for (long pos = offset; pos < offset + length; pos += readSize) { |
| 164 | if (offset + length - pos < bufferSize) { |
| 165 | bufferSize = (int)(offset + length - pos); |
| 166 | } |
| 167 | long begin = System.currentTimeMillis(); |
| 168 | readSize = in.read(pos, buffer, 0, bufferSize); |
| 169 | logger.debug("CopyPartially read time cost: {}, bufferSize: {}", |
| 170 | System.currentTimeMillis() - begin, bufferSize); |
| 171 | if (readSize == -1) { |
| 172 | logger.warn("CopyPartially EOF path: {}, pos: {}, totalLength: {}", |
| 173 | new Object[] {path, pos, stat.getLen()}); |
| 174 | return; |
| 175 | } |
| 176 | if (readSize != bufferSize) { |
| 177 | logger.warn("CopyPartially readSize: {}, bufferSize: {}", readSize, bufferSize); |
| 178 | } |
| 179 | out.write(buffer, 0, readSize); |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | } |