1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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-29 07:15:24 +0100 (Mi, 29 Nov 2006) $
28 */
29 public class FileUtil
30 {
31 private FileUtil()
32 {
33 }
34
35 /***
36 * Returns the content of a file, as a byte array.
37 *
38 * @param file The file to get the content of.
39 */
40 public static byte[] getContent(final FileObject file)
41 throws IOException
42 {
43 final FileContent content = file.getContent();
44 final int size = (int) content.getSize();
45 final byte[] buf = new byte[size];
46
47 final InputStream in = content.getInputStream();
48 try
49 {
50 int read = 0;
51 for (int pos = 0; pos < size && read >= 0; pos += read)
52 {
53 read = in.read(buf, pos, size - pos);
54 }
55 }
56 finally
57 {
58 in.close();
59 }
60
61 return buf;
62 }
63
64 /***
65 * Writes the content of a file to an OutputStream.
66 */
67 public static void writeContent(final FileObject file,
68 final OutputStream outstr)
69 throws IOException
70 {
71 final InputStream instr = file.getContent().getInputStream();
72 try
73 {
74 final byte[] buffer = new byte[1024];
75 while (true)
76 {
77 final int nread = instr.read(buffer);
78 if (nread < 0)
79 {
80 break;
81 }
82 outstr.write(buffer, 0, nread);
83 }
84 }
85 finally
86 {
87 instr.close();
88 }
89 }
90
91 /***
92 * Copies the content from a source file to a destination file.
93 */
94 public static void copyContent(final FileObject srcFile,
95 final FileObject destFile)
96 throws IOException
97 {
98
99
100 final OutputStream outstr = destFile.getContent().getOutputStream();
101 try
102 {
103 writeContent(srcFile, outstr);
104 }
105 finally
106 {
107 outstr.close();
108 }
109 }
110
111 }