View Javadoc

    1   /**
    2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
    3    */
    4   package net.sourceforge.pmd.util.datasource;
    5
    6   import java.io.File;
    7   import java.io.FileInputStream;
    8   import java.io.IOException;
    9   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(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  }