PageRenderTime 52ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/projects/azureus-4.7.0.2/org/pf/file/FileUtil.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 468 lines | 256 code | 60 blank | 152 comment | 36 complexity | 6e633233b93406697f92da079d62e9ae MD5 | raw file
  1. // ===========================================================================
  2. // CONTENT : CLASS FileUtil
  3. // AUTHOR : Manfred Duchrow
  4. // VERSION : 1.1 - 14/03/2003
  5. // HISTORY :
  6. // 17/05/2002 duma CREATED
  7. // 14/03/2003 duma added -> standardize(), javaFilename()
  8. //
  9. // Copyright (c) 2002-2003, by Manfred Duchrow. All rights reserved.
  10. // ===========================================================================
  11. package org.pf.file ;
  12. // ===========================================================================
  13. // IMPORTS
  14. // ===========================================================================
  15. import java.io.* ;
  16. import org.pf.text.StringUtil;
  17. /**
  18. * This class provides helper methods for file and stream handling.
  19. * It's an add-on to the java.io package.
  20. * The service is implemented as a singleton, so use the
  21. * <b>FileUtil.current()</b> method to get the sole instance.
  22. *
  23. * @author Manfred Duchrow
  24. * @version 1.1
  25. */
  26. public class FileUtil
  27. {
  28. // =========================================================================
  29. // CONSTANTS
  30. // =========================================================================
  31. /** The lines.separator from the system properties as a constant */
  32. public static final String LINE_SEPARATOR = System.getProperty( "line.separator" ) ;
  33. protected static final int DEFAULT_BUFFER_SIZE = 1024 ;
  34. // =========================================================================
  35. // CLASS VARIABLES
  36. // =========================================================================
  37. private static FileUtil current = new FileUtil() ;
  38. // =========================================================================
  39. // CLASS METHODS
  40. // =========================================================================
  41. // =========================================================================
  42. // CONSTRUCTORS
  43. // =========================================================================
  44. /**
  45. * Initialize the new instance with default values.
  46. */
  47. private FileUtil()
  48. {
  49. super() ;
  50. } // FileUtil()
  51. // =========================================================================
  52. // PUBLIC CLASS METHODS
  53. // =========================================================================
  54. public static FileUtil current()
  55. {
  56. return current ;
  57. } // current()
  58. // =========================================================================
  59. // PUBLIC INSTANCE METHODS
  60. // =========================================================================
  61. /**
  62. * Copies all data from the iniput stream to the output stream using
  63. * a buffer with the default size (1024 bytes).
  64. * After all data is copied both streams will be closed !
  65. */
  66. public void copyStream( InputStream inStream, OutputStream outStream )
  67. throws IOException
  68. {
  69. this.copyStream( inStream, outStream, DEFAULT_BUFFER_SIZE ) ;
  70. } // copyStream()
  71. // -------------------------------------------------------------------------
  72. /**
  73. * Copies all data from the iniput stream to the output stream using
  74. * a buffer of the given size in bytes.
  75. * After all data is copied both streams will be closed !
  76. */
  77. public void copyStream( InputStream inStream, OutputStream outStream,
  78. int bufSize )
  79. throws IOException
  80. {
  81. byte[] buffer = new byte[bufSize] ;
  82. int count ;
  83. try
  84. {
  85. count = inStream.read(buffer) ;
  86. while ( count > -1 )
  87. {
  88. outStream.write( buffer, 0, count ) ;
  89. count = inStream.read(buffer) ;
  90. }
  91. }
  92. finally
  93. {
  94. this.close(inStream) ;
  95. this.close(outStream) ;
  96. }
  97. } // copyStream()
  98. // -------------------------------------------------------------------------
  99. /**
  100. * Reads the whole content of the given input stream and returns
  101. * it as a string.
  102. * The stream will be closed after calling this method. Even if an exception
  103. * occured!
  104. *
  105. * @param inStream The input stream to read
  106. * @return The text content of the given stream
  107. */
  108. public String readTextFrom( InputStream inStream )
  109. throws IOException
  110. {
  111. StringWriter writer ;
  112. writer = new StringWriter( 1024 ) ;
  113. this.copyText( inStream, writer ) ;
  114. return writer.toString() ;
  115. } // readTextFrom()
  116. // -------------------------------------------------------------------------
  117. /**
  118. * Reads the whole content of the file with the given name and returns
  119. * it as a string.
  120. *
  121. * @param filename The name of the text containing file
  122. */
  123. public String readTextFrom( String filename )
  124. throws IOException
  125. {
  126. FileInputStream inStream ;
  127. inStream = new FileInputStream( filename ) ;
  128. return this.readTextFrom( inStream ) ;
  129. } // readTextFrom()
  130. // -------------------------------------------------------------------------
  131. /**
  132. * Reads the whole content of the specified file and returns
  133. * it as a string.
  134. */
  135. public String readTextFrom( File file )
  136. throws IOException
  137. {
  138. FileInputStream inStream ;
  139. inStream = new FileInputStream( file ) ;
  140. return this.readTextFrom( inStream ) ;
  141. } // readTextFrom()
  142. // -------------------------------------------------------------------------
  143. /**
  144. * Copies all text lines from the specified reader to the given writer.
  145. * After that the reader will be closed. Even if an exception occurs.
  146. *
  147. * @param reader The reader which provides the text to copy
  148. * @param writer The writer to which the text will be copied
  149. */
  150. public void copyText( Reader reader, final StringWriter writer )
  151. throws IOException
  152. {
  153. BufferedReader bufReader ;
  154. String line ;
  155. LineProcessor processor ;
  156. bufReader = new BufferedReader( reader ) ;
  157. try
  158. {
  159. processor = new LineProcessor()
  160. {
  161. public boolean processLine( String line, int lineNo )
  162. {
  163. if ( lineNo > 1 )
  164. writer.write( LINE_SEPARATOR ) ;
  165. writer.write( line ) ;
  166. return true ;
  167. }
  168. } ;
  169. this.processTextLines( bufReader, processor ) ;
  170. }
  171. finally
  172. {
  173. bufReader.close() ;
  174. }
  175. } // copyText()
  176. // ------------------------------------------------------------------------
  177. /**
  178. * Reads all text lines from the file with the specified name and passes them
  179. * one by one to the given line processor.
  180. * The processing will be terminated, if the end of the text is reached or
  181. * if the processor returns <b>false</b>.<br>
  182. *
  183. * @param filename The name of the text file to read
  184. * @param processor The processor that receives the lines from the text
  185. */
  186. public void processTextLines( String filename, LineProcessor processor )
  187. throws IOException
  188. {
  189. FileInputStream inStream ;
  190. if ( filename == null )
  191. throw new IllegalArgumentException( "filename must not be null" ) ;
  192. inStream = new FileInputStream( filename ) ;
  193. this.processTextLines( inStream, processor ) ;
  194. } // processTextLines()
  195. // -------------------------------------------------------------------------
  196. /**
  197. * Reads all text lines from the specified input stream and passes them
  198. * one by one to the given line processor.
  199. * The processing will be terminated, if the end of the text is reached or
  200. * if the processor returns <b>false</b>.<br>
  201. * The given input stream will be closed after the execution of this method.
  202. * Even if an exception occured.
  203. *
  204. * @param inStream The input stream that contains the text
  205. * @param processor The processor that receives the lines from the text
  206. */
  207. public void processTextLines( InputStream inStream, LineProcessor processor )
  208. throws IOException
  209. {
  210. InputStreamReader reader ;
  211. if ( inStream == null )
  212. throw new IllegalArgumentException( "inStream must not be null" ) ;
  213. reader = new InputStreamReader( inStream ) ;
  214. this.processTextLines( reader, processor ) ;
  215. } // processTextLines()
  216. // -------------------------------------------------------------------------
  217. /**
  218. * Reads all text lines from the specified reader and passes them one by one
  219. * to the given line processor.
  220. * The processing will be terminated, if the end of the text is reached or
  221. * if the processor returns <b>false</b>.
  222. *
  223. * @param reader The reader that contains a text stream
  224. * @param processor The processor that receives the lines from the text
  225. */
  226. public void processTextLines( Reader reader, LineProcessor processor )
  227. throws IOException
  228. {
  229. BufferedReader bufReader ;
  230. String line ;
  231. int counter = 0 ;
  232. boolean continue_reading = true ;
  233. if ( reader == null )
  234. throw new IllegalArgumentException( "reader must not be null" ) ;
  235. if ( processor == null )
  236. throw new IllegalArgumentException( "processor must not be null" ) ;
  237. bufReader = new BufferedReader( reader ) ;
  238. while ( continue_reading && bufReader.ready() )
  239. {
  240. line = bufReader.readLine() ;
  241. if ( line == null )
  242. break ;
  243. counter++ ;
  244. continue_reading = processor.processLine( line, counter ) ;
  245. }
  246. } // processTextLines()
  247. // ------------------------------------------------------------------------
  248. /**
  249. * Close the given stream ignoring any exception.
  250. * Returns true, if the stream was closed successfully, false otherwise
  251. */
  252. public boolean close( InputStream stream )
  253. {
  254. if ( stream == null )
  255. {
  256. return false ;
  257. }
  258. try
  259. {
  260. stream.close() ;
  261. return true ;
  262. }
  263. catch (IOException e)
  264. {
  265. return false ;
  266. }
  267. } // close()
  268. // -------------------------------------------------------------------------
  269. /**
  270. * Close the given stream ignoring any exception.
  271. * Returns true, if the stream was closed successfully, false otherwise
  272. */
  273. public boolean close( OutputStream stream )
  274. {
  275. if ( stream == null )
  276. {
  277. return false ;
  278. }
  279. try
  280. {
  281. stream.close() ;
  282. return true ;
  283. }
  284. catch (IOException e)
  285. {
  286. return false ;
  287. }
  288. } // close()
  289. // -------------------------------------------------------------------------
  290. /**
  291. * Convert the filename to a canonical (see java.io.File.getCanonicalPath())
  292. * format and replace any backslashes '\' by slashes ('/').
  293. * If possible all "." and ".." elements in the path are eliminated.
  294. *
  295. * @param filename The filename which has to be standardized
  296. * @return An absolute filename that uses slashes to separate its elements
  297. */
  298. public String standardize( String filename )
  299. {
  300. if ( filename == null )
  301. return null ;
  302. return this.standardizeFilename( filename ) ;
  303. } // standardize()
  304. // -------------------------------------------------------------------------
  305. /**
  306. * Returns the given filename in the platform independent way that Java
  307. * understands. That is all elements are separated by a forward slash rather
  308. * than back slashes as on Windows systems.
  309. *
  310. * @param filename The name to be modified
  311. */
  312. public String javaFilename( String filename )
  313. {
  314. if ( filename == null )
  315. return null ;
  316. return filename.replace( '\\', '/' ) ;
  317. } // javaFilename()
  318. // -------------------------------------------------------------------------
  319. // =========================================================================
  320. // PROTECTED INSTANCE METHODS
  321. // =========================================================================
  322. protected void copyText( InputStream inStream, StringWriter writer )
  323. throws IOException
  324. {
  325. this.copyText( new InputStreamReader( inStream ), writer ) ;
  326. } // copyText()
  327. // ------------------------------------------------------------------------
  328. protected String standardizeFilename( String filename )
  329. {
  330. String[] nameElements ;
  331. boolean hasDriveLetter ;
  332. boolean startedFromRoot ;
  333. boolean isAbsolute ;
  334. int index ;
  335. filename = this.javaFilename(filename) ;
  336. startedFromRoot = filename.startsWith( "/" ) ;
  337. nameElements = this.str().parts( filename, "/" ) ;
  338. if ( nameElements.length > 0 )
  339. {
  340. hasDriveLetter = nameElements[0].endsWith( ":" ) ;
  341. if ( hasDriveLetter )
  342. {
  343. nameElements[0] = nameElements[0].toUpperCase() ;
  344. }
  345. else
  346. {
  347. if ( startedFromRoot )
  348. {
  349. nameElements = this.str().append( new String[] { "" }, nameElements );
  350. }
  351. }
  352. isAbsolute = hasDriveLetter || startedFromRoot ;
  353. for (int i = 0; i < nameElements.length; i++)
  354. {
  355. if ( ".".equals( nameElements[i] ) )
  356. {
  357. nameElements[i] = null ;
  358. }
  359. else
  360. {
  361. if ( "..".equals( nameElements[i] ) )
  362. {
  363. index = this.indexOfPreceedingNotNullElement( nameElements, i-1 ) ;
  364. if ( index >= 0 )
  365. {
  366. if ( ( index > 0 ) || ( ! isAbsolute ) )
  367. {
  368. nameElements[i] = null ;
  369. nameElements[index] = null ;
  370. }
  371. }
  372. }
  373. }
  374. }
  375. nameElements = this.str().removeNull( nameElements ) ;
  376. return this.str().asString( nameElements, "/" ) ;
  377. }
  378. else
  379. {
  380. return "" ;
  381. }
  382. } // standardizeFilename()
  383. // -------------------------------------------------------------------------
  384. protected int indexOfPreceedingNotNullElement( String[] elements, int start )
  385. {
  386. for (int i = start; i >= 0 ; i--)
  387. {
  388. if ( elements[i] != null )
  389. {
  390. if ( "..".equals( elements[i] ) ) // This is not a valid not null element
  391. {
  392. return -1 ;
  393. }
  394. else
  395. {
  396. return i ;
  397. }
  398. }
  399. }
  400. return -1 ;
  401. } // indexOfPreceedingNotNullElement()
  402. // -------------------------------------------------------------------------
  403. protected StringUtil str()
  404. {
  405. return StringUtil.current() ;
  406. } // str()
  407. // -------------------------------------------------------------------------
  408. } // class FileUtil