001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.vfs2; 018 019import java.io.IOException; 020import java.io.InputStream; 021import java.io.OutputStream; 022 023/** 024 * Utility methods for dealing with FileObjects. 025 */ 026public final class FileUtil { 027 028 private FileUtil() { 029 } 030 031 /** 032 * Returns the content of a file, as a byte array. 033 * 034 * @param file The file to get the content of. 035 * @return The content as a byte array. 036 * @throws IOException if the file content cannot be accessed. 037 */ 038 public static byte[] getContent(final FileObject file) throws IOException { 039 final FileContent content = file.getContent(); 040 final int size = (int) content.getSize(); 041 final byte[] buf = new byte[size]; 042 043 final InputStream in = content.getInputStream(); 044 try { 045 int read = 0; 046 for (int pos = 0; pos < size && read >= 0; pos += read) { 047 read = in.read(buf, pos, size - pos); 048 } 049 } finally { 050 in.close(); 051 } 052 053 return buf; 054 } 055 056 /** 057 * Writes the content of a file to an OutputStream. 058 * 059 * @param file The FileObject to write. 060 * @param output The OutputStream to write to. 061 * @throws IOException if an error occurs writing the file. 062 * @see FileContent#write(OutputStream) 063 */ 064 public static void writeContent(final FileObject file, final OutputStream output) throws IOException { 065 file.getContent().write(output); 066 } 067 068 /** 069 * Copies the content from a source file to a destination file. 070 * 071 * @param srcFile The source FileObject. 072 * @param destFile The target FileObject 073 * @throws IOException If an error occurs copying the file. 074 * @see FileContent#write(FileContent) 075 * @see FileContent#write(FileObject) 076 */ 077 public static void copyContent(final FileObject srcFile, final FileObject destFile) throws IOException { 078 srcFile.getContent().write(destFile); 079 } 080 081}