PageRenderTime 118ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/extension/src/main/java/org/springside/modules/utils/FileUtils.java

https://github.com/yangjiandong/sshapp
Java | 432 lines | 224 code | 55 blank | 153 comment | 33 complexity | f2981a1a540853833829622aa928b8c1 MD5 | raw file
  1. package org.springside.modules.utils;
  2. /*
  3. Milyn - Copyright (C) 2006
  4. This library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License (version 2.1) as published by the Free Software
  7. Foundation.
  8. This library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. See the GNU Lesser General Public License for more details:
  12. http://www.gnu.org/licenses/lgpl.txt
  13. */
  14. import java.io.BufferedInputStream;
  15. import java.io.BufferedOutputStream;
  16. import java.io.BufferedReader;
  17. import java.io.ByteArrayOutputStream;
  18. import java.io.File;
  19. import java.io.FileInputStream;
  20. import java.io.FileOutputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.io.InputStreamReader;
  24. import java.io.OutputStream;
  25. import java.io.Reader;
  26. import java.io.StringReader;
  27. import java.nio.channels.FileChannel;
  28. import java.nio.charset.Charset;
  29. import java.util.zip.ZipEntry;
  30. import java.util.zip.ZipOutputStream;
  31. /**
  32. * File utilities.
  33. *
  34. * @author <a href="mailto:tom.fennelly@jboss.com">tom.fennelly@jboss.com</a>
  35. * @author <a href="mailto:quest.run@gmail.com">pprun</a>
  36. */
  37. public abstract class FileUtils {
  38. /**
  39. * Read the contents of the specified file.
  40. * @param file The file to read.
  41. * @return The file contents as byte array.
  42. * @throws IOException Error readiong file.
  43. */
  44. public static byte[] readFile(File file) throws IOException {
  45. if (!file.exists()) {
  46. throw new IllegalArgumentException("No such file '" + file.getAbsoluteFile() + "'.");
  47. } else if (file.isDirectory()) {
  48. throw new IllegalArgumentException("File '" + file.getAbsoluteFile() + "' is a directory. Cannot read.");
  49. }
  50. InputStream stream = new FileInputStream(file);
  51. try {
  52. return StreamUtils.readStream(stream);
  53. } finally {
  54. stream.close();
  55. }
  56. }
  57. /**
  58. * Read the contents of the specified file.
  59. * @param file The file to read.
  60. * @return The file contents as String.
  61. * @throws IOException Error readiong file.
  62. */
  63. public static String readFileAsString(File file) throws IOException {
  64. if (!file.exists()) {
  65. throw new IllegalArgumentException("No such file '" + file.getAbsoluteFile() + "'.");
  66. } else if (file.isDirectory()) {
  67. throw new IllegalArgumentException("File '" + file.getAbsoluteFile() + "' is a directory. Cannot read.");
  68. }
  69. InputStream stream = new FileInputStream(file);
  70. try {
  71. return StreamUtils.readStreamAsString(stream);
  72. } finally {
  73. stream.close();
  74. }
  75. }
  76. public static void writeFile(byte[] bytes, File file) throws IOException {
  77. if (file.isDirectory()) {
  78. throw new IllegalArgumentException("File '" + file.getAbsoluteFile() + "' is an existing directory. Cannot write.");
  79. }
  80. FileOutputStream stream = new FileOutputStream(file);
  81. try {
  82. stream.write(bytes);
  83. stream.flush();
  84. } finally {
  85. stream.close();
  86. }
  87. }
  88. public static void copyFile(String from, String to) throws IOException {
  89. File fromFile = new File(from);
  90. File toFile = new File(to);
  91. writeFile(readFile(fromFile), toFile);
  92. }
  93. /**
  94. * normalize the path
  95. * @param path
  96. * @return
  97. */
  98. public static String getPath(String dir) {
  99. String path = dir;
  100. if (path != null && !path.endsWith(File.separator)) {
  101. path += File.separator;
  102. }
  103. return path;
  104. }
  105. /**
  106. * normalize the path, using the passed in separator, this is used for
  107. * remote path such as FTP servers file path;
  108. * @param path
  109. * @return
  110. */
  111. public static String getPath(String dir, String separator) {
  112. String path = dir;
  113. if (path != null
  114. && !path.endsWith(separator)
  115. && !path.endsWith(File.separator)) {
  116. path += separator;
  117. }
  118. return path;
  119. }
  120. /**
  121. * This method will create the structure of the directory path if it hasn't
  122. * existed.
  123. *
  124. * @param path the directory path to be test.
  125. * @return
  126. */
  127. public static File ensureDirExist(String path) {
  128. File dir = new File(path);
  129. if (dir.exists()) {
  130. if (!dir.isDirectory()) {
  131. throw new IllegalArgumentException("Existing file with same name for the directory already exists");
  132. }
  133. // else we are fine.
  134. } else {
  135. if (!dir.mkdirs()) {
  136. throw new IllegalArgumentException("Cannot create directory : " + path);
  137. }
  138. }
  139. return dir;
  140. }
  141. /**
  142. * While creating a new file, it the file existing, append an increasing number to the file name.
  143. * @param path
  144. * @return the file but the actual file was not created until a actually IO wrapper, such as FileStreamOutput wrapped
  145. * it and write content.
  146. */
  147. public static File getNewFile(String path, String fileName, String extension) {
  148. if (extension != null && extension.isEmpty() == false) {
  149. extension = "." + extension;
  150. } else {
  151. extension = "";
  152. }
  153. File file = new File(path + File.separator + fileName + extension);
  154. int i = 0;
  155. while (file.exists()) {
  156. // existing? append a increasing number
  157. file = new File(path + File.separator + fileName + "_" + ++i + extension);
  158. }
  159. return file;
  160. }
  161. /**
  162. * Zip the <tt>sourceFile</tt> into <tt>toFile</tt>.
  163. *
  164. * @param sourceFile
  165. * @param toFile
  166. * @throws java.io.IOException
  167. */
  168. public static void zip(File fromFile, File toFile) throws IOException {
  169. zip(new FileInputStream(fromFile), toFile);
  170. }
  171. /**
  172. * zip the contents of an {@link InputStream}. Note that once the
  173. * zip file has been created, the {@link InputStream} will be closed.
  174. * @param is
  175. * @param toFile
  176. * @throws IOException
  177. */
  178. public static void zip(InputStream is, File toFile) throws IOException {
  179. zip(is, toFile, true);
  180. }
  181. /**
  182. * zip the contents of an {@link InputStream}. Note that once the
  183. * zip file has been created, the {@link InputStream} will be closed.
  184. * @param is
  185. * @param toFile
  186. * @throws IOException
  187. */
  188. public static void zip(InputStream is, File toFile, boolean closeInputStream) throws IOException {
  189. final int BUFFER_SIZE = 2048;
  190. BufferedInputStream in = new BufferedInputStream(is, BUFFER_SIZE);
  191. try {
  192. ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(toFile)));
  193. try {
  194. // just the name instead of full path + name
  195. ZipEntry entry = new ZipEntry(toFile.getName());
  196. out.putNextEntry(entry);
  197. byte data[] = new byte[BUFFER_SIZE];
  198. int count;
  199. while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) {
  200. out.write(data, 0, count);
  201. }
  202. } finally {
  203. out.close();
  204. }
  205. } finally {
  206. if (closeInputStream) {
  207. in.close();
  208. }
  209. }
  210. }
  211. /**
  212. * Copy file from one to another
  213. * @param in
  214. * @param out
  215. * @throws Exception
  216. */
  217. public static void copyFile(File in, File out) throws IOException {
  218. FileChannel sourceChannel = new FileInputStream(in).getChannel();
  219. try {
  220. FileChannel destinationChannel = new FileOutputStream(out).getChannel();
  221. try {
  222. sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
  223. } finally {
  224. destinationChannel.close();
  225. }
  226. } finally {
  227. sourceChannel.close();
  228. }
  229. }
  230. }
  231. /**
  232. * Stream Utilities.
  233. *
  234. * @author tfennelly
  235. */
  236. abstract class StreamUtils {
  237. /**
  238. * Read the supplied InputStream and return as a byte array.
  239. *
  240. * @param stream
  241. * The stream to read.
  242. * @return byte array containing the Stream data.
  243. * @throws IOException
  244. * Exception reading from the stream.
  245. */
  246. public static byte[] readStream(InputStream stream) throws IOException {
  247. ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
  248. byte[] byteBuf = new byte[1024];
  249. int readCount = 0;
  250. while ((readCount = stream.read(byteBuf)) != -1) {
  251. bytesOut.write(byteBuf, 0, readCount);
  252. }
  253. return bytesOut.toByteArray();
  254. }
  255. /**
  256. * Read the supplied InputStream and return as a byte array.
  257. *
  258. * @param stream
  259. * The stream to read.
  260. * @return A String containing the Stream data.
  261. * @throws IOException
  262. * Exception reading from the stream.
  263. */
  264. public static String readStreamAsString(InputStream stream) throws IOException {
  265. return new String(readStream(stream), Charset.forName("UTF-8"));
  266. }
  267. public static byte[] readFile(File file) throws IOException {
  268. InputStream stream = new FileInputStream(file);
  269. try {
  270. return readStream(stream);
  271. } finally {
  272. stream.close();
  273. }
  274. }
  275. public static void writeFile(File file, byte[] data) throws IOException {
  276. OutputStream stream = new FileOutputStream(file);
  277. try {
  278. stream.write(data);
  279. } finally {
  280. try {
  281. stream.flush();
  282. } finally {
  283. stream.close();
  284. }
  285. }
  286. }
  287. public static String readStream(Reader stream) throws IOException {
  288. StringBuilder streamString = new StringBuilder();
  289. char[] readBuffer = new char[256];
  290. int readCount = 0;
  291. while ((readCount = stream.read(readBuffer)) != -1) {
  292. streamString.append(readBuffer, 0, readCount);
  293. }
  294. return streamString.toString();
  295. }
  296. /**
  297. * Compares the 2 streams.
  298. * <p/>
  299. * Calls {@link #trimLines(InputStream)} on each stream before comparing.
  300. * @param s1 Stream 1.
  301. * @param s2 Stream 2.
  302. * @return True if the streams are equal not including leading and trailing
  303. * whitespace on each line and blank lines, otherwise returns false.
  304. */
  305. public static boolean compareCharStreams(InputStream s1, InputStream s2) {
  306. StringBuffer s1Buf, s2Buf;
  307. try {
  308. s1Buf = trimLines(s1);
  309. s2Buf = trimLines(s2);
  310. return s1Buf.toString().equals(s2Buf.toString());
  311. } catch (IOException e) {
  312. // fail the comparison
  313. }
  314. return false;
  315. }
  316. /**
  317. * Compares the 2 streams.
  318. * <p/>
  319. * Calls {@link #trimLines(java.io.Reader)} on each stream before comparing.
  320. * @param s1 Stream 1.
  321. * @param s2 Stream 2.
  322. * @return True if the streams are equal not including leading and trailing
  323. * whitespace on each line and blank lines, otherwise returns false.
  324. */
  325. public static boolean compareCharStreams(Reader s1, Reader s2) {
  326. StringBuffer s1Buf, s2Buf;
  327. try {
  328. s1Buf = trimLines(s1);
  329. s2Buf = trimLines(s2);
  330. return s1Buf.toString().equals(s2Buf.toString());
  331. } catch (IOException e) {
  332. // fail the comparison
  333. }
  334. return false;
  335. }
  336. /**
  337. * Compares the 2 streams.
  338. * <p/>
  339. * Calls {@link #trimLines(java.io.Reader)} on each stream before comparing.
  340. * @param s1 Stream 1.
  341. * @param s2 Stream 2.
  342. * @return True if the streams are equal not including leading and trailing
  343. * whitespace on each line and blank lines, otherwise returns false.
  344. */
  345. public static boolean compareCharStreams(String s1, String s2) {
  346. return compareCharStreams(new StringReader(s1), new StringReader(s2));
  347. }
  348. /**
  349. * Read the lines lines of characters from the stream and trim each line
  350. * i.e. remove all leading and trailing whitespace.
  351. * @param charStream Character stream.
  352. * @return StringBuffer containing the line trimmed stream.
  353. * @throws IOException
  354. */
  355. public static StringBuffer trimLines(Reader charStream) throws IOException {
  356. StringBuffer stringBuf = new StringBuffer();
  357. BufferedReader reader = new BufferedReader(charStream);
  358. String line;
  359. while ((line = reader.readLine()) != null) {
  360. stringBuf.append(line.trim());
  361. }
  362. return stringBuf;
  363. }
  364. /**
  365. * Read the lines lines of characters from the stream and trim each line
  366. * i.e. remove all leading and trailing whitespace.
  367. * @param charStream Character stream.
  368. * @return StringBuffer containing the line trimmed stream.
  369. * @throws IOException
  370. */
  371. public static StringBuffer trimLines(InputStream charStream) throws IOException {
  372. return trimLines(new InputStreamReader(charStream, "UTF-8"));
  373. }
  374. }