View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *  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  
18  package org.apache.any23.source;
19  
20  import java.io.BufferedInputStream;
21  import java.io.ByteArrayOutputStream;
22  import java.io.File;
23  import java.io.FileInputStream;
24  import java.io.IOException;
25  import java.io.InputStream;
26  
27  /**
28   * File implementation of {@link DocumentSource}.
29   */
30  public class FileDocumentSource implements DocumentSource {
31  
32      private final File file;
33  
34      private final String uri;
35  
36      public FileDocumentSource(File file) {
37          this.file = file;
38          this.uri = file.toURI().toString();
39      }
40  
41      public FileDocumentSource(File file, String baseIRI) {
42          this.file = file;
43          this.uri = baseIRI;
44      }
45  
46      public InputStream openInputStream() throws IOException {
47          return new BufferedInputStream( new FileInputStream(file) );
48      }
49  
50      public long getContentLength() {
51          return file.length();
52      }
53  
54      public String getDocumentIRI() {
55          return uri;
56      }
57  
58      public String getContentType() {
59          return null;
60      }
61  
62      public boolean isLocal() {
63          return true;
64      }
65  
66      public String readStream() throws IOException {
67          final ByteArrayOutputStream baos = new ByteArrayOutputStream();
68          InputStream is = openInputStream();
69          try {
70              int c;
71              while ((c = is.read()) != -1) {
72                  baos.write(c);
73              }
74          } finally {
75              is.close();
76          }
77          return new String( baos.toByteArray() );
78      }
79  }