01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17: package org.apache.commons.vfs;
18:
19: import java.io.IOException;
20: import java.io.InputStream;
21: import java.io.OutputStream;
22:
23: /**
24: * Utility methods for dealng with FileObjects.
25: *
26: * @author <a href="mailto:adammurdoch@apache.org">Adam Murdoch</a>
27: * @version $Revision: 480428 $ $Date: 2006-11-28 22:15:24 -0800 (Tue, 28 Nov 2006) $
28: */
29: public class FileUtil {
30: private FileUtil() {
31: }
32:
33: /**
34: * Returns the content of a file, as a byte array.
35: *
36: * @param file The file to get the content of.
37: */
38: public static byte[] getContent(final FileObject file)
39: throws IOException {
40: final FileContent content = file.getContent();
41: final int size = (int) content.getSize();
42: final byte[] buf = new byte[size];
43:
44: final InputStream in = content.getInputStream();
45: try {
46: int read = 0;
47: for (int pos = 0; pos < size && read >= 0; pos += read) {
48: read = in.read(buf, pos, size - pos);
49: }
50: } finally {
51: in.close();
52: }
53:
54: return buf;
55: }
56:
57: /**
58: * Writes the content of a file to an OutputStream.
59: */
60: public static void writeContent(final FileObject file,
61: final OutputStream outstr) throws IOException {
62: final InputStream instr = file.getContent().getInputStream();
63: try {
64: final byte[] buffer = new byte[1024];
65: while (true) {
66: final int nread = instr.read(buffer);
67: if (nread < 0) {
68: break;
69: }
70: outstr.write(buffer, 0, nread);
71: }
72: } finally {
73: instr.close();
74: }
75: }
76:
77: /**
78: * Copies the content from a source file to a destination file.
79: */
80: public static void copyContent(final FileObject srcFile,
81: final FileObject destFile) throws IOException {
82: // Create the output stream via getContent(), to pick up the
83: // validation it does
84: final OutputStream outstr = destFile.getContent()
85: .getOutputStream();
86: try {
87: writeContent(srcFile, outstr);
88: } finally {
89: outstr.close();
90: }
91: }
92:
93: }
|