1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, 13 * software distributed under the License is distributed on an 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 * KIND, either express or implied. See the License for the 16 * specific language governing permissions and limitations 17 * under the License. 18 */ 19 package org.apache.commons.compress.archivers.zip; 20 21 import java.io.IOException; 22 import java.nio.ByteBuffer; 23 import java.nio.channels.FileChannel; 24 import java.nio.channels.SeekableByteChannel; 25 26 /** 27 * IO utilities for Zip operations. 28 */ 29 // Keep package-private; consider for Apache Commons IO. 30 class ZipIoUtil { 31 32 /** 33 * Writes full buffer to channel. 34 * 35 * @param channel channel to write to 36 * @param buf buffer to write 37 * @throws IOException when writing fails or fails to write fully 38 */ 39 static void writeFully(final SeekableByteChannel channel, final ByteBuffer buf) throws IOException { 40 while (buf.hasRemaining()) { 41 final int remaining = buf.remaining(); 42 final int written = channel.write(buf); 43 if (written <= 0) { 44 throw new IOException("Failed to fully write: channel=" + channel + " length=" + remaining + " written=" + written); 45 } 46 } 47 } 48 49 /** 50 * Writes full buffer to channel at specified position. 51 * 52 * @param channel channel to write to 53 * @param buf buffer to write 54 * @param position position to write at 55 * @throws IOException when writing fails or fails to write fully 56 */ 57 static void writeFullyAt(final FileChannel channel, final ByteBuffer buf, final long position) throws IOException { 58 for (long currentPosition = position; buf.hasRemaining();) { 59 final int remaining = buf.remaining(); 60 final int written = channel.write(buf, currentPosition); 61 if (written <= 0) { 62 throw new IOException("Failed to fully write: channel=" + channel + " length=" + remaining + " written=" + written); 63 } 64 currentPosition += written; 65 } 66 } 67 68 private ZipIoUtil() { 69 } 70 }