View Javadoc
1   package org.apache.struts.scripting;
2   
3   import java.io.BufferedReader;
4   import java.io.IOException;
5   import java.io.Reader;
6   import java.nio.file.Files;
7   import java.nio.file.Path;
8   import java.nio.file.attribute.BasicFileAttributes;
9   import java.nio.file.attribute.FileTime;
10  
11  /**
12   * Supporter class for {@code Struts-Scripting}.
13   *
14   * @author Stefan Graff
15   *
16   * @since Struts 1.4.1
17   */
18  class IOUtils {
19  
20      private IOUtils() {}
21  
22      /**
23       * Reads from the give {@code Path} the last modified time. If
24       * the given {@code Path} is {@code null}, {@code null} will be
25       * returned.
26       *
27       * @param path the given {@code Path}
28       *
29       * @return the last modified time or {@code null} if the given
30       *     {@code Path} is {@code null}
31       *
32       * @throws IOException if an I/O error occurs
33       */
34      static FileTime getLastModifiedTime(final Path path) throws IOException {
35          if (path == null) {
36              return null;
37          }
38  
39          BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
40          return attr.lastModifiedTime();
41      }
42  
43      /**
44       * Reads all lines from {@code Reader} and save it
45       * into a {@code String}.
46       *
47       * @param reader the given {@code Reader}
48       *
49       * @return the whole text from {@code Reader}
50       *
51       * @throws IOException if an I/O error occurs
52       */
53      static String getStringFromReader(Reader reader) throws IOException {
54          try (BufferedReader br = reader instanceof BufferedReader
55                  ? (BufferedReader)reader
56                  : new BufferedReader(reader)) {
57  
58              final String lineSeparator = System.lineSeparator();
59              final StringBuilder sb = new StringBuilder(8 * 1024);
60  
61              String line;
62              while ((line = br.readLine()) != null) {
63                  sb.append(lineSeparator).append(line);
64              }
65  
66              return sb.substring(sb.length() ==  0 ? 0 : lineSeparator.length());
67          }
68      }
69  }