FileDataSource.java
01 /**
02  * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03  */
04 package net.sourceforge.pmd.util.datasource;
05 
06 import java.io.File;
07 import java.io.FileInputStream;
08 import java.io.IOException;
09 import java.io.InputStream;
10 
11 
12 /**
13  * DataSource implementation to read data from a file.
14  */
15 public class FileDataSource implements DataSource {
16   
17   private static final String FILE_SEPARATOR = System.getProperty("file.separator");
18   
19     private File file;
20 
21     /**
22      @param file the file to read
23      */
24     public FileDataSource(File file) {
25         this.file = file;
26     }
27 
28     public InputStream getInputStream() throws IOException {
29         return new FileInputStream(file);
30     }
31 
32     public String getNiceFileName(boolean shortNames, String inputFileName) {
33         return glomName(shortNames, inputFileName, file);
34     }
35 
36     private String glomName(boolean shortNames, String inputFileName, File file) {
37         if (shortNames && inputFileName.indexOf(','== -1) {
38             if (new File(inputFileName).isDirectory()) {
39                 return trimAnyPathSep(file.getAbsolutePath().substring(inputFileName.length()));
40             else {
41                 if (inputFileName.indexOf(FILE_SEPARATOR.charAt(0)) == -1) {
42                     return inputFileName;
43                 }
44                 return trimAnyPathSep(inputFileName.substring(inputFileName.lastIndexOf(System.getProperty("file.separator"))));
45             }
46         
47 
48         try {
49             return file.getCanonicalFile().getAbsolutePath();
50         catch (Exception e) {
51             return file.getAbsolutePath();
52         }
53     }
54 
55     private String trimAnyPathSep(String name) {
56 
57       return name.startsWith(FILE_SEPARATOR?
58             name.substring(1:
59             name;
60     }
61 }