You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FileUtils.java 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. /*
  2. * Copyright 2011 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.gitblit.utils;
  17. import java.io.BufferedInputStream;
  18. import java.io.BufferedReader;
  19. import java.io.BufferedWriter;
  20. import java.io.File;
  21. import java.io.FileInputStream;
  22. import java.io.FileNotFoundException;
  23. import java.io.FileOutputStream;
  24. import java.io.IOException;
  25. import java.io.InputStreamReader;
  26. import java.io.OutputStreamWriter;
  27. import java.nio.charset.Charset;
  28. /**
  29. * Common file utilities.
  30. *
  31. * @author James Moger
  32. *
  33. */
  34. public class FileUtils {
  35. /** 1024 (number of bytes in one kilobyte) */
  36. public static final int KB = 1024;
  37. /** 1024 {@link #KB} (number of bytes in one megabyte) */
  38. public static final int MB = 1024 * KB;
  39. /** 1024 {@link #MB} (number of bytes in one gigabyte) */
  40. public static final int GB = 1024 * MB;
  41. /**
  42. * Returns an int from a string representation of a file size.
  43. * e.g. 50m = 50 megabytes
  44. *
  45. * @param aString
  46. * @param defaultValue
  47. * @return an int value or the defaultValue if aString can not be parsed
  48. */
  49. public static int convertSizeToInt(String aString, int defaultValue) {
  50. return (int) convertSizeToLong(aString, defaultValue);
  51. }
  52. /**
  53. * Returns a long from a string representation of a file size.
  54. * e.g. 50m = 50 megabytes
  55. *
  56. * @param aString
  57. * @param defaultValue
  58. * @return a long value or the defaultValue if aString can not be parsed
  59. */
  60. public static long convertSizeToLong(String aString, long defaultValue) {
  61. // trim string and remove all spaces
  62. aString = aString.toLowerCase().trim();
  63. StringBuilder sb = new StringBuilder();
  64. for (String a : aString.split(" ")) {
  65. sb.append(a);
  66. }
  67. aString = sb.toString();
  68. // identify value and unit
  69. int idx = 0;
  70. int len = aString.length();
  71. while (Character.isDigit(aString.charAt(idx))) {
  72. idx++;
  73. if (idx == len) {
  74. break;
  75. }
  76. }
  77. long value = 0;
  78. String unit = null;
  79. try {
  80. value = Long.parseLong(aString.substring(0, idx));
  81. unit = aString.substring(idx);
  82. } catch (Exception e) {
  83. return defaultValue;
  84. }
  85. if (unit.equals("g") || unit.equals("gb")) {
  86. return value * GB;
  87. } else if (unit.equals("m") || unit.equals("mb")) {
  88. return value * MB;
  89. } else if (unit.equals("k") || unit.equals("kb")) {
  90. return value * KB;
  91. }
  92. return defaultValue;
  93. }
  94. /**
  95. * Returns the byte [] content of the specified file.
  96. *
  97. * @param file
  98. * @return the byte content of the file
  99. */
  100. public static byte [] readContent(File file) {
  101. byte [] buffer = new byte[(int) file.length()];
  102. BufferedInputStream is = null;
  103. try {
  104. is = new BufferedInputStream(new FileInputStream(file));
  105. is.read(buffer, 0, buffer.length);
  106. } catch (Throwable t) {
  107. System.err.println("Failed to read byte content of " + file.getAbsolutePath());
  108. t.printStackTrace();
  109. } finally {
  110. if (is != null) {
  111. try {
  112. is.close();
  113. } catch (IOException ioe) {
  114. System.err.println("Failed to close file " + file.getAbsolutePath());
  115. ioe.printStackTrace();
  116. }
  117. }
  118. }
  119. return buffer;
  120. }
  121. /**
  122. * Returns the string content of the specified file.
  123. *
  124. * @param file
  125. * @param lineEnding
  126. * @return the string content of the file
  127. */
  128. public static String readContent(File file, String lineEnding) {
  129. StringBuilder sb = new StringBuilder();
  130. InputStreamReader is = null;
  131. try {
  132. is = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"));
  133. BufferedReader reader = new BufferedReader(is);
  134. String line = null;
  135. while ((line = reader.readLine()) != null) {
  136. sb.append(line);
  137. if (lineEnding != null) {
  138. sb.append(lineEnding);
  139. }
  140. }
  141. } catch (Throwable t) {
  142. System.err.println("Failed to read content of " + file.getAbsolutePath());
  143. t.printStackTrace();
  144. } finally {
  145. if (is != null) {
  146. try {
  147. is.close();
  148. } catch (IOException ioe) {
  149. System.err.println("Failed to close file " + file.getAbsolutePath());
  150. ioe.printStackTrace();
  151. }
  152. }
  153. }
  154. return sb.toString();
  155. }
  156. /**
  157. * Writes the string content to the file.
  158. *
  159. * @param file
  160. * @param content
  161. */
  162. public static void writeContent(File file, String content) {
  163. OutputStreamWriter os = null;
  164. try {
  165. os = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8"));
  166. BufferedWriter writer = new BufferedWriter(os);
  167. writer.append(content);
  168. writer.flush();
  169. } catch (Throwable t) {
  170. System.err.println("Failed to write content of " + file.getAbsolutePath());
  171. t.printStackTrace();
  172. } finally {
  173. if (os != null) {
  174. try {
  175. os.close();
  176. } catch (IOException ioe) {
  177. System.err.println("Failed to close file " + file.getAbsolutePath());
  178. ioe.printStackTrace();
  179. }
  180. }
  181. }
  182. }
  183. /**
  184. * Recursively traverses a folder and its subfolders to calculate the total
  185. * size in bytes.
  186. *
  187. * @param directory
  188. * @return folder size in bytes
  189. */
  190. public static long folderSize(File directory) {
  191. if (directory == null || !directory.exists()) {
  192. return -1;
  193. }
  194. if (directory.isDirectory()) {
  195. long length = 0;
  196. for (File file : directory.listFiles()) {
  197. length += folderSize(file);
  198. }
  199. return length;
  200. } else if (directory.isFile()) {
  201. return directory.length();
  202. }
  203. return 0;
  204. }
  205. /**
  206. * Copies a file or folder (recursively) to a destination folder.
  207. *
  208. * @param destinationFolder
  209. * @param filesOrFolders
  210. * @return
  211. * @throws FileNotFoundException
  212. * @throws IOException
  213. */
  214. public static void copy(File destinationFolder, File... filesOrFolders)
  215. throws FileNotFoundException, IOException {
  216. destinationFolder.mkdirs();
  217. for (File file : filesOrFolders) {
  218. if (file.isDirectory()) {
  219. copy(new File(destinationFolder, file.getName()), file.listFiles());
  220. } else {
  221. File dFile = new File(destinationFolder, file.getName());
  222. BufferedInputStream bufin = null;
  223. FileOutputStream fos = null;
  224. try {
  225. bufin = new BufferedInputStream(new FileInputStream(file));
  226. fos = new FileOutputStream(dFile);
  227. int len = 8196;
  228. byte[] buff = new byte[len];
  229. int n = 0;
  230. while ((n = bufin.read(buff, 0, len)) != -1) {
  231. fos.write(buff, 0, n);
  232. }
  233. } finally {
  234. try {
  235. if (bufin != null) bufin.close();
  236. } catch (Throwable t) {
  237. }
  238. try {
  239. if (fos != null) fos.close();
  240. } catch (Throwable t) {
  241. }
  242. }
  243. dFile.setLastModified(file.lastModified());
  244. }
  245. }
  246. }
  247. /**
  248. * Determine the relative path between two files. Takes into account
  249. * canonical paths, if possible.
  250. *
  251. * @param basePath
  252. * @param path
  253. * @return a relative path from basePath to path
  254. */
  255. public static String getRelativePath(File basePath, File path) {
  256. File exactBase = getExactFile(basePath);
  257. File exactPath = getExactFile(path);
  258. if (path.getAbsolutePath().startsWith(basePath.getAbsolutePath())) {
  259. // absolute base-path match
  260. return StringUtils.getRelativePath(basePath.getAbsolutePath(), path.getAbsolutePath());
  261. } else if (exactPath.getPath().startsWith(exactBase.getPath())) {
  262. // canonical base-path match
  263. return StringUtils.getRelativePath(exactBase.getPath(), exactPath.getPath());
  264. } else if (exactPath.getPath().startsWith(basePath.getAbsolutePath())) {
  265. // mixed path match
  266. return StringUtils.getRelativePath(basePath.getAbsolutePath(), exactPath.getPath());
  267. } else if (path.getAbsolutePath().startsWith(exactBase.getPath())) {
  268. // mixed path match
  269. return StringUtils.getRelativePath(exactBase.getPath(), path.getAbsolutePath());
  270. }
  271. // no relative relationship
  272. return null;
  273. }
  274. /**
  275. * Returns the exact path for a file. This path will be the canonical path
  276. * unless an exception is thrown in which case it will be the absolute path.
  277. *
  278. * @param path
  279. * @return the exact file
  280. */
  281. public static File getExactFile(File path) {
  282. try {
  283. return path.getCanonicalFile();
  284. } catch (IOException e) {
  285. return path.getAbsoluteFile();
  286. }
  287. }
  288. public static File resolveParameter(String parameter, File aFolder, String path) {
  289. if (aFolder == null) {
  290. // strip any parameter reference
  291. path = path.replace(parameter, "").trim();
  292. if (path.length() > 0 && path.charAt(0) == '/') {
  293. // strip leading /
  294. path = path.substring(1);
  295. }
  296. } else if (path.contains(parameter)) {
  297. // replace parameter with path
  298. path = path.replace(parameter, aFolder.getAbsolutePath());
  299. }
  300. return new File(path);
  301. }
  302. }