/src/com/atlassian/uwc/ui/FileUtils.java

https://bitbucket.org/atlassianlabs/universal-wiki-connector · Java · 214 lines · 124 code · 19 blank · 71 comment · 14 complexity · c54c270e75519b4a19d46ca27952c6d2 MD5 · raw file

  1. package com.atlassian.uwc.ui;
  2. import org.apache.log4j.Logger;
  3. import java.io.*;
  4. import java.nio.charset.Charset;
  5. import java.util.zip.GZIPInputStream;
  6. /**
  7. * A couple of random file functions that are used by the engine.
  8. * User: Rex (Rolf Staflin)
  9. * Date: 2006-apr-05
  10. * Time: 16:39:31
  11. */
  12. public class FileUtils {
  13. static final Logger log = Logger.getLogger(FileUtils.class);
  14. /**
  15. * Make sure the output directory exists
  16. */
  17. public static void createOutputDirIfNeeded() {
  18. File outputDir = new File("output");
  19. if (!outputDir.exists()) {
  20. outputDir.mkdir();
  21. }
  22. }
  23. /**
  24. * Reads a text file into a String object line by line, converting line breaks to the local format.
  25. *
  26. * @param inputFile The name of and path to the file
  27. * @param charset The Charset of the file
  28. * @return a String with the file contents.
  29. * @throws java.io.IOException
  30. */
  31. public static String readTextFile(File inputFile, Charset charset) throws IOException {
  32. FileInputStream fis = new FileInputStream(inputFile);
  33. InputStreamReader isr = new InputStreamReader(fis, charset);
  34. BufferedReader reader = new BufferedReader(isr);
  35. StringBuffer contents = new StringBuffer();
  36. String line;
  37. String separator = System.getProperty("line.separator");
  38. while (( line = reader.readLine()) != null){
  39. contents.append(line).append(separator);
  40. }
  41. fis.close();
  42. isr.close();
  43. return contents.toString();
  44. }
  45. /**
  46. * Reads a text file into a String object line by line, converting line breaks to the local format.
  47. *
  48. * @todo The character set is hard coded to UTF-8, but it should be configurable by the user.
  49. * The best thing would be to fill a combo box with all available character sets, obtained from
  50. * Charset.availableCharsets().
  51. *
  52. * @param inputFile The name of and path to the file
  53. * @return a String with the file contents.
  54. * @throws java.io.IOException
  55. */
  56. public static String readTextFile(File inputFile) throws IOException {
  57. Charset charset = Charset.forName("UTF-8");
  58. return readTextFile(inputFile, charset);
  59. }
  60. public static String readGzipFile(File file) throws IOException {
  61. FileInputStream fis = new FileInputStream(file);
  62. GZIPInputStream gis = new GZIPInputStream(fis);
  63. InputStreamReader isr = new InputStreamReader(gis);
  64. BufferedReader reader = new BufferedReader(isr);
  65. StringBuffer contents = new StringBuffer();
  66. String line;
  67. String separator = System.getProperty("line.separator");
  68. while (( line = reader.readLine()) != null){
  69. contents.append(line).append(separator);
  70. }
  71. fis.close();
  72. isr.close();
  73. return contents.toString();
  74. }
  75. /**
  76. * Creates or truncates a file and then writes a string to it.
  77. *
  78. * Note that errors are not reported from this method.
  79. *
  80. * @param text The text to be written
  81. * @param filePath The file name or path
  82. */
  83. public static void writeFile(String text, String filePath) {
  84. BufferedWriter writer = null;
  85. try {
  86. //writer = new BufferedWriter(new FileWriter(filePath));
  87. writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath),"UTF8"));
  88. writer.write(text);
  89. } catch (IOException e) {
  90. String message = "Error writing to file " + filePath +
  91. "\n" +
  92. "Note: Output file cannot be written to disk. Check permissions.";
  93. log.error(message, e);
  94. } finally {
  95. if (writer != null) {
  96. try {
  97. writer.close();
  98. } catch (IOException ignored) {
  99. // Do nothing
  100. }
  101. }
  102. }
  103. }
  104. /**
  105. * Writes bytes to the given filePath
  106. * @param bytes
  107. * @param filePath
  108. * @return true, if write was successful.
  109. * if false, one of several problems occurred.
  110. * Possibly: couldn't find file, couldn'y write to file, or
  111. * couldn't close file.
  112. * Check logs for error messages.
  113. */
  114. public static boolean writeFile(byte[] bytes, String filePath) {
  115. FileOutputStream out = null;
  116. log.debug("Preparing to write to file: " + filePath);
  117. try {
  118. out = new FileOutputStream(filePath);
  119. } catch (FileNotFoundException e) {
  120. log.error("Could not create outputstream for file: " + filePath);
  121. e.printStackTrace();
  122. return false;
  123. }
  124. try {
  125. out.write(bytes);
  126. } catch (IOException e) {
  127. log.error("Problem writing bytes to " + filePath);
  128. e.printStackTrace();
  129. return false;
  130. } finally {
  131. try {
  132. out.close();
  133. } catch (IOException e) {
  134. log.error("Problem closing file: " + filePath);
  135. e.printStackTrace();
  136. return false;
  137. }
  138. }
  139. log.debug("Wrote bytes to file successfully.");
  140. return true;
  141. }
  142. /**
  143. * Returns the contents of the file in a byte array. A byte array is
  144. * what we can pass to XMLRPC-Confluence to upload an attachment
  145. * (copied from O'Reilly)
  146. */
  147. public static byte[] getBytesFromFile(File file) throws IOException {
  148. InputStream is = new FileInputStream(file);
  149. // Get the size of the file
  150. long length = file.length();
  151. // You cannot create an array using a long type.
  152. // It needs to be an int type.
  153. // Before converting to an int type, check
  154. // to ensure that file is not larger than Integer.MAX_VALUE.
  155. if (length > Integer.MAX_VALUE) {
  156. // File is too large
  157. }
  158. // Create the byte array to hold the data
  159. byte[] bytes = new byte[(int) length];
  160. // Read in the bytes
  161. int offset = 0;
  162. int numRead = 0;
  163. while (offset < bytes.length
  164. && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
  165. offset += numRead;
  166. }
  167. // Ensure all the bytes have been read in
  168. if (offset < bytes.length) {
  169. throw new IOException("Could not completely read file " + file.getName());
  170. }
  171. // Close the input stream and return bytes
  172. is.close();
  173. return bytes;
  174. }
  175. /**
  176. * recursively deletes a directory.
  177. * If the passed file is a file, it will simply delete it.
  178. * It the passed file is a directory, it will delete it and all it's contents.
  179. * If the passed file does not exist, it will be ignored.
  180. * @param dir
  181. */
  182. public static void deleteDir(File dir) {
  183. if (!dir.exists()) return; //if the directory isn't existing, then ignore it
  184. if (!dir.isDirectory()) {
  185. dir.delete(); //delete a file
  186. return;
  187. }
  188. //look through each file and delete them
  189. File[] files = dir.listFiles();
  190. for (File file : files) {
  191. deleteDir(file);
  192. }
  193. dir.delete(); //delete the empty directory
  194. }
  195. }