r2140 - in trunk/nuiton-utils/src: main/java/org/nuiton/util test/java/org/nuiton/util test/resources/org/nuiton/util
Author: tchemit Date: 2011-05-15 12:35:01 +0200 (Sun, 15 May 2011) New Revision: 2140 Url: http://nuiton.org/repositories/revision/nuiton-utils/2140 Log: Reformat some files (80 caracters max) Anomalie #1528: There is a *testdir* created over and over while building library Anomalie #1530: Tests for grep methods depends on java source files Evolution #1529: Add some usefull methods to obtain files from paths or fqn Added: trunk/nuiton-utils/src/test/resources/org/nuiton/util/fileUtilData.txt Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/FileUtil.java trunk/nuiton-utils/src/test/java/org/nuiton/util/FileUtilTest.java trunk/nuiton-utils/src/test/java/org/nuiton/util/ResourceTest.java trunk/nuiton-utils/src/test/java/org/nuiton/util/ZipUtilTest.java Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/FileUtil.java =================================================================== --- trunk/nuiton-utils/src/main/java/org/nuiton/util/FileUtil.java 2011-05-14 11:44:58 UTC (rev 2139) +++ trunk/nuiton-utils/src/main/java/org/nuiton/util/FileUtil.java 2011-05-15 10:35:01 UTC (rev 2140) @@ -36,6 +36,10 @@ package org.nuiton.util; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JFileChooser; import java.awt.Component; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; @@ -66,11 +70,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.swing.JFileChooser; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - /** * Opérations sur des fichiers. Copie, suppression, renommage, * recherche, fichiers d'un répertoire, sous-répertoires d'un répertoire, @@ -161,7 +160,8 @@ * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé * @see #getFile(javax.swing.filechooser.FileFilter...) */ - static public File getFile(Component parent, String... patternOrDescriptionFilters) { + static public File getFile(Component parent, + String... patternOrDescriptionFilters) { File result; result = getFile("Ok", "Ok", parent, patternOrDescriptionFilters); return result; @@ -179,12 +179,16 @@ * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé * @see #getFile(javax.swing.filechooser.FileFilter...) */ - static public File getFile(String title, String approvalText, Component parent, String... patternOrDescriptionFilters) { + static public File getFile(String title, + String approvalText, + Component parent, + String... patternOrDescriptionFilters) { if (patternOrDescriptionFilters.length % 2 != 0) { throw new IllegalArgumentException("Arguments must be (pattern, description) couple"); } - javax.swing.filechooser.FileFilter[] filters = new javax.swing.filechooser.FileFilter[patternOrDescriptionFilters.length / 2]; + javax.swing.filechooser.FileFilter[] filters = + new javax.swing.filechooser.FileFilter[patternOrDescriptionFilters.length / 2]; for (int i = 0; i < filters.length; i++) { String pattern = patternOrDescriptionFilters[i * 2]; String description = patternOrDescriptionFilters[i * 2 + 1]; @@ -204,7 +208,8 @@ * @param filters les filtres a ajouter * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé */ - static public File getFile(Component parent, javax.swing.filechooser.FileFilter... filters) { + static public File getFile(Component parent, + javax.swing.filechooser.FileFilter... filters) { File result = getFile("Ok", "Ok", parent, filters); return result; } @@ -219,7 +224,10 @@ * @param filters les filtres a ajouter * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé */ - static public File getFile(String title, String approvalText, Component parent, javax.swing.filechooser.FileFilter... filters) { + static public File getFile(String title, + String approvalText, + Component parent, + javax.swing.filechooser.FileFilter... filters) { try { JFileChooser chooser = new JFileChooser(currentDirectory); @@ -279,7 +287,9 @@ * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne * null. */ - static public String getDirectory(Component parent, String title, String approvalText) { + static public String getDirectory(Component parent, + String title, + String approvalText) { try { JFileChooser chooser = new JFileChooser(currentDirectory); chooser.setDialogType(JFileChooser.CUSTOM_DIALOG); @@ -311,15 +321,21 @@ * @throws IOException if any io pb */ static public byte[] fileToByte(File file) throws IOException { + ByteArrayOutputStream result; InputStream in = new BufferedInputStream(new FileInputStream(file)); - ByteArrayOutputStream result = new ByteArrayOutputStream(); - BufferedOutputStream tmp = new BufferedOutputStream(result); - for (int b = in.read(); b != -1; b = in.read()) { - tmp.write(b); + try { + result = new ByteArrayOutputStream(); + BufferedOutputStream tmp = new BufferedOutputStream(result); + try { + for (int b = in.read(); b != -1; b = in.read()) { + tmp.write(b); + } + } finally { + tmp.close(); + } + } finally { + in.close(); } - in.close(); - tmp.close(); - return result.toByteArray(); } @@ -342,11 +358,14 @@ ByteArrayOutputStream result = new ByteArrayOutputStream(); BufferedOutputStream tmp = new BufferedOutputStream(result); - for (int b = src.read(); b != -1; b = src.read()) { - tmp.write(b); + try { + for (int b = src.read(); b != -1; b = src.read()) { + tmp.write(b); + } + src.close(); + } finally { + tmp.close(); } - src.close(); - tmp.close(); byteToFile(result.toByteArray(), dst); return dst; } @@ -373,7 +392,8 @@ * @return le fichier passé en parametre * @throws IOException if any io pb */ - static public File byteToFile(byte[] bytes, File file) throws IOException { + static public File byteToFile(byte[] bytes, + File file) throws IOException { OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { out.write(bytes); @@ -403,7 +423,8 @@ * @return the buffered reader in the given encoding * @throws IOException if any io pb */ - static public BufferedReader getReader(File file, String encoding) throws IOException { + static public BufferedReader getReader(File file, + String encoding) throws IOException { FileInputStream inf = new FileInputStream(file); InputStreamReader in = new InputStreamReader(inf, encoding); BufferedReader result = new BufferedReader(in); @@ -430,7 +451,8 @@ * @return the buffered writer on the given file with given encoding * @throws IOException if any io pb */ - static public BufferedWriter getWriter(File file, String encoding) throws IOException { + static public BufferedWriter getWriter(File file, + String encoding) throws IOException { FileOutputStream outf = new FileOutputStream(file); OutputStreamWriter out = new OutputStreamWriter(outf, encoding); BufferedWriter result = new BufferedWriter(out); @@ -449,7 +471,9 @@ * @return le fichier pointant sur le nouveau repertoire * @throws IOException if any io pb */ - static public File createTempDirectory(String prefix, String suffix, File tmpdir) throws IOException { + static public File createTempDirectory(String prefix, + String suffix, + File tmpdir) throws IOException { if (tmpdir == null) { tmpdir = new File(System.getProperty("java.io.tmpdir")); } @@ -472,7 +496,8 @@ * @return the temprary created file * @throws IOException if any io pb */ - static public File createTempDirectory(String prefix, String suffix) throws IOException { + static public File createTempDirectory(String prefix, + String suffix) throws IOException { return createTempDirectory(prefix, suffix, null); } @@ -518,10 +543,13 @@ * @param content Le texte a ecrire dans le fichier * @throws IOException if any pb while writing */ - static public void writeString(File file, String content) throws IOException { + static public void writeString(File file, + String content) throws IOException { //fixme on doit tester le retour de la méthode, car il se peut que le répertoire // ne puisse etre cree. File parentFile = file.getParentFile(); + //TODO tchemit 2011-05-15 Must test if directory was created (use + // the #createDirectoryIfNecessary method). if (parentFile != null) { parentFile.mkdirs(); } @@ -539,10 +567,14 @@ * @param encoding encoding to use * @throws IOException if any pb while writing */ - static public void writeString(File file, String content, String encoding) throws IOException { + static public void writeString(File file, + String content, + String encoding) throws IOException { //fixme on doit tester le retour de la méthode, car il se peut que le répertoire // ne puisse être crée. File parentFile = file.getParentFile(); + //TODO tchemit 2011-05-15 Must test if directory was created (use + // the #createDirectoryIfNecessary method). if (parentFile != null) { parentFile.mkdirs(); } @@ -573,8 +605,10 @@ * @return le fichier qui contient content * @throws IOException if any io pb */ - static public File getTempFile(String content, String fileSuffix) throws IOException { - File result = File.createTempFile("tmp-" + FileUtil.class.getName(), fileSuffix); + static public File getTempFile(String content, + String fileSuffix) throws IOException { + File result = File.createTempFile("tmp-" + FileUtil.class.getName(), + fileSuffix); result.deleteOnExit(); writeString(result, content); return result; @@ -608,7 +642,8 @@ String result = name; for (String suffixe : suffixes) { if (result.endsWith(suffixe)) { - result = result.substring(0, result.length() - suffixe.length()); + result = result.substring(0, + result.length() - suffixe.length()); break; } } @@ -691,9 +726,11 @@ String... extchars) throws IOException { String extension = extension(name, extchars); if (extension == null) { - throw new IOException("Could not find extension for name " + name + " within " + Arrays.toString(extchars)); + throw new IOException("Could not find extension for name " + + name + " within " + Arrays.toString(extchars)); } - String nameWithoutExtension = name.substring(0, name.length() - extension.length()); + String nameWithoutExtension = name.substring( + 0, name.length() - extension.length()); String newName = nameWithoutExtension + newExtension; return newName; } @@ -775,7 +812,9 @@ * @return une liste d'objet {@link File} qui ont s'attisfait le * pattern. */ - public static List<File> find(File directory, final String pattern, boolean recursively) { + public static List<File> find(File directory, + final String pattern, + boolean recursively) { final String root = directory.getAbsolutePath(); final int rootLength = root.length(); @@ -800,7 +839,9 @@ * @param recursively un flag pour indiquer si on doit descendre dans les répertoires * @return une liste d'objet {@link File}, qui s'attisfont le filtre */ - public static List<File> getFilteredElements(File directory, FileFilter ff, boolean recursively) { + public static List<File> getFilteredElements(File directory, + FileFilter ff, + boolean recursively) { ArrayList<File> result = new ArrayList<File>(); LinkedList<File> todo = new LinkedList<File>(); if (directory.isDirectory()) { @@ -810,7 +851,8 @@ File file = todo.removeFirst(); if (recursively && file.isDirectory()) { File[] childs = file.listFiles(); - if (childs != null) { // null if we don't have access to directory + if (childs != null) { + // null if we don't have access to directory todo.addAll(Arrays.asList(childs)); } } @@ -902,14 +944,26 @@ public static void copy(File source, File target) throws IOException { //fixme on doit tester le retour de la méthode, car il se peut que le répertoire // ne puisse être copié. + //TODO tchemit 2011-05-15 Must test if directory was created (use + // the #createDirectoryIfNecessary method). target.getParentFile().mkdirs(); - FileChannel sourceChannel = new FileInputStream(source).getChannel(); - FileChannel targetChannel = new FileOutputStream(target).getChannel(); - sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); - // or - // targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); - sourceChannel.close(); - targetChannel.close(); + FileInputStream fileInputStream = new FileInputStream(source); + try { + FileChannel sourceChannel = fileInputStream.getChannel(); + FileOutputStream fileOutputStream = new FileOutputStream(target); + try { + FileChannel targetChannel = fileOutputStream.getChannel(); + sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); + // or + // targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); + targetChannel.close(); + } finally { + fileOutputStream.close(); + } + sourceChannel.close(); + } finally { + fileInputStream.close(); + } } /** @@ -935,7 +989,9 @@ * fichiers/repertoires pour etre copié. Si vide alors tout est copié * @throws IOException if any io pb */ - static public void copyRecursively(File srcDir, File destDir, String... includePatterns) throws IOException { + static public void copyRecursively(File srcDir, + File destDir, + String... includePatterns) throws IOException { copyAndRenameRecursively(srcDir, destDir, null, null, includePatterns); } @@ -955,8 +1011,17 @@ * @throws IOException if any io pb */ static public void copyAndRenameRecursively(File srcDir, File destDir, - String renameFrom, String renameTo, String... includePatterns) throws IOException { - copyAndRenameRecursively(srcDir, destDir, true, renameFrom, renameTo, false, includePatterns); + String renameFrom, + String renameTo, + String... includePatterns) throws IOException { + copyAndRenameRecursively(srcDir, + destDir, + true, + renameFrom, + renameTo, + false, + includePatterns + ); } /** @@ -977,8 +1042,12 @@ * fichiers/repertoires pour etre copié. Si vide alors tout est copié * @throws IOException if any io pb */ - static public void copyAndRenameRecursively(File srcDir, File destDir, - boolean includeSrcDir, String renameFrom, String renameTo, boolean exclude, + static public void copyAndRenameRecursively(File srcDir, + File destDir, + boolean includeSrcDir, + String renameFrom, + String renameTo, + boolean exclude, String... includePatterns) throws IOException { String rootSrc; if (includeSrcDir) { @@ -1042,7 +1111,8 @@ * @param includePatterns les patterns pour accepeter le fichier depuis son nom * @return <code>true</code> si le fichier est accepté, <code>false> autrement. */ - private static boolean copyRecursivelyAccept(File file, String[] includePatterns) { + private static boolean copyRecursivelyAccept(File file, + String[] includePatterns) { boolean result = includePatterns.length == 0; String filename = file.getAbsolutePath(); for (String pattern : includePatterns) { @@ -1068,7 +1138,8 @@ * @throws IOException * @since 1.1.2 */ - protected static List<CharSequence> grep(String regex, CharBuffer cb) { + protected static List<CharSequence> grep(String regex, + CharBuffer cb) { List<CharSequence> linesList = null; @@ -1117,7 +1188,9 @@ * @throws IOException * @since 1.1.2 */ - public static List<CharSequence> grep(String searchRegex, File f, String encoding) throws IOException { + public static List<CharSequence> grep(String searchRegex, + File f, + String encoding) throws IOException { List<CharSequence> lines = null; @@ -1165,9 +1238,13 @@ * @throws IOException * @since 1.1.2 */ - public static Map<File, List<CharSequence>> grep(String searchRegex, File rootDirectory, String fileRegex, String encoding) throws IOException { - Map<File, List<CharSequence>> results = new HashMap<File, List<CharSequence>>(); - List<File> files = FileUtil.find(rootDirectory, fileRegex, true); + public static Map<File, List<CharSequence>> grep(String searchRegex, + File rootDirectory, + String fileRegex, + String encoding) throws IOException { + Map<File, List<CharSequence>> results = + new HashMap<File, List<CharSequence>>(); + List<File> files = find(rootDirectory, fileRegex, true); for (File file : files) { List<CharSequence> lines = grep(searchRegex, file, encoding); if (lines != null) { @@ -1187,8 +1264,13 @@ * @throws IOException * @since 1.1.2 */ - public static Map<File, List<CharSequence>> grep(String searchRegex, String fileRegex, String encoding) throws IOException { - Map<File, List<CharSequence>> results = grep(searchRegex, new File("."), fileRegex, encoding); + public static Map<File, List<CharSequence>> grep(String searchRegex, + String fileRegex, + String encoding) throws IOException { + Map<File, List<CharSequence>> results = grep(searchRegex, + new File("."), + fileRegex, + encoding); return results; } @@ -1204,15 +1286,17 @@ * @throws IOException * @since 1.1.2 */ - public static void sed(String searchRegex, String replace, File file, String encoding) throws IOException { + public static void sed(String searchRegex, + String replace, + File file, + String encoding) throws IOException { Pattern pattern = Pattern.compile(searchRegex); - FileInputStream fis = null; String outString = null; + FileInputStream fis = new FileInputStream(file); try { // Open the file and then get a channel from the stream - fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); // Get the file's size and then map it into memory @@ -1227,25 +1311,17 @@ Matcher matcher = pattern.matcher(cb); outString = matcher.replaceAll(replace); + } finally { + fis.close(); } - finally { - if (fis != null) { - fis.close(); - } - } if (outString != null) { - PrintStream ps = null; + PrintStream ps = new PrintStream(new FileOutputStream(file)); try { - ps = new PrintStream(new FileOutputStream(file)); ps.print(outString); + } finally { ps.close(); } - finally { - if (ps != null) { - ps.close(); - } - } } } @@ -1260,8 +1336,12 @@ * @throws IOException * @since 1.1.2 */ - public static void sed(String searchRegex, String replace, File rootDirectory, String fileRegex, String encoding) throws IOException { - List<File> files = FileUtil.find(rootDirectory, fileRegex, true); + public static void sed(String searchRegex, + String replace, + File rootDirectory, + String fileRegex, + String encoding) throws IOException { + List<File> files = find(rootDirectory, fileRegex, true); for (File file : files) { sed(searchRegex, replace, file, encoding); } @@ -1277,7 +1357,10 @@ * @throws IOException * @since 1.1.2 */ - public static void sed(String searchRegex, String replace, String fileRegex, String encoding) throws IOException { + public static void sed(String searchRegex, + String replace, + String fileRegex, + String encoding) throws IOException { sed(searchRegex, replace, new File("."), fileRegex, encoding); } @@ -1302,4 +1385,45 @@ return false; } + /** + * Obtain a file from the given {@code rootDirectory}, applying given paths. + * <p/> + * For example with paths = a, b and c, then result is : + * <pre> + * root/a/b/c + * </pre> + * + * @param rootDirectory the root directory + * @param paths paths to apply + * @return the final file + * @since 2.2 + */ + public static File getFileFromPaths(File rootDirectory, String... paths) { + File result = rootDirectory; + for (String path : paths) { + result = new File(result, path); + } + return result; + } + + /** + * Obtain a file fro the given {@code rootDirectory}, applying the fqn. + * <p/> + * For example with fqn = a.b.c, the result is : + * <pre> + * root/a/b/c + * </pre> + * + * @param rootDirectory the root directory + * @param fqn fqn of searched file + * @return the final file + * @since 2.2 + */ + public static File getFileFromFQN(File rootDirectory, String fqn) { + String[] paths = fqn.split("\\."); + + File result = getFileFromPaths(rootDirectory, paths); + return result; + } + } // FileUtil Modified: trunk/nuiton-utils/src/test/java/org/nuiton/util/FileUtilTest.java =================================================================== --- trunk/nuiton-utils/src/test/java/org/nuiton/util/FileUtilTest.java 2011-05-14 11:44:58 UTC (rev 2139) +++ trunk/nuiton-utils/src/test/java/org/nuiton/util/FileUtilTest.java 2011-05-15 10:35:01 UTC (rev 2140) @@ -25,25 +25,26 @@ package org.nuiton.util; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - /** * FileUtilTest. - * + * <p/> * Created: 22 nov. 2004 * * @author Benjamin Poussin <poussin@codelutin.com> * @version $Revision$ - * - * Mise a jour: $Date$ - * par : */ + * <p/> + * Mise a jour: $Date$ + * par : + */ public class FileUtilTest { // FileUtilTest @Test @@ -67,7 +68,7 @@ result = FileUtil.extension(new File("/tmp/toto.xml"), "t", "."); Assert.assertEquals("o.xml", result); } - + @Test public void testWriteString() throws IOException { File testFile = new File(System.getProperty("java.io.tmpdir"), "test.txt"); @@ -76,10 +77,10 @@ Assert.assertEquals("testWriteString", FileUtil.readAsString(testFile)); } - + /** * This test throwed NPE before 1.2.1 with simple file path (current folder). - * + * * @throws IOException */ @Test @@ -90,15 +91,18 @@ Assert.assertEquals("testWriteString", FileUtil.readAsString(testFile)); } - + /** * Test testWriteString method with file containing ".." - * + * * @throws IOException */ @Test public void testWriteStringRelativeNonCanonical() throws IOException { - File testFile = new File(".." + File.separator + "testdir" + File.separator + "test.txt"); + File testFile = new File(".." + File.separator + + "target" + File.separator + + "surefire-workdir" + File.separator + + "testdir" + File.separator + "test.txt"); testFile.deleteOnExit(); FileUtil.writeString(testFile, "testWriteString"); @@ -122,7 +126,7 @@ FileUtil.copyRecursively(srcDir, destDir1); FileUtil.copyRecursively(srcDir, destDir2, ".*titi$"); - + // remove created temp dirs : FileUtil.deleteRecursively(srcDir); FileUtil.deleteRecursively(destDir1); @@ -144,55 +148,56 @@ Assert.assertEquals(file.length(), dest.length()); Assert.assertEquals(content, FileUtil.readAsString(dest)); } - + /** * Test grep on a single file. - * + * <p/> * Search for grep() method count. - * - * @throws IOException + * + * @throws IOException */ @Test public void testGrepSingleFile() throws IOException { // search for - File testUtilFile = FileUtil.find(new File("."), ".*FileUtil\\.java", true).get(0); + File testUtilFile = FileUtil.find(new File("."), ".*fileUtilData\\.txt", true).get(0); - List<CharSequence> lines = FileUtil.grep("grep\\(String .*\\)", testUtilFile , "UTF-8"); + List<CharSequence> lines = FileUtil.grep("grep\\(String .*\\)", testUtilFile, "UTF-8"); Assert.assertNotNull(lines); Assert.assertEquals(4, lines.size()); - + // assert result are ordered - Assert.assertTrue(lines.get(0).toString().indexOf("CharBuffer") > 0); - Assert.assertTrue(lines.get(1).toString().indexOf("File f,") > 0); - Assert.assertTrue(lines.get(2).toString().indexOf("rootDirectory") > 0); - Assert.assertTrue(lines.get(3).toString().indexOf("String searchRegex, String fileRegex, String encoding") > 0); + Assert.assertTrue(lines.get(0).toString().contains("CharBuffer")); + Assert.assertTrue(lines.get(1).toString().contains("File f,")); + Assert.assertTrue(lines.get(2).toString().contains("rootDirectory")); + Assert.assertTrue(lines.get(3).toString().contains("String searchRegex, String fileRegex, String encoding")); } - + /** * Test grep on a multiple files. - * + * <p/> * Try to find all java file containing "CodeLutin". Can fail if some * src files are deleted. - * - * @throws IOException + * + * @throws IOException */ @Test public void testGrepMultiple() throws IOException { File rootDir = new File("src"); - Map<File, List<CharSequence>> results = FileUtil.grep("CodeLutin", rootDir , ".*\\.java", "UTF-8"); + Map<File, List<CharSequence>> results = FileUtil.grep("CodeLutin", rootDir, ".*\\.java", "UTF-8"); - Assert.assertTrue("should have more than 50 files, but found : "+ + Assert.assertTrue("should have more than 50 files, but found : " + results.size(), results.size() > 50); - + } - + /** * Test sed method on a single file. - * @throws IOException + * + * @throws IOException */ @Test public void testSedSingleFile() throws IOException { @@ -201,34 +206,34 @@ // try to not make sed in real src dir ;) File testDirectory = FileUtil.createTempDirectory("sed", "test"); FileUtil.copyRecursively(new File("src").getAbsoluteFile(), testDirectory); - File testUtilFile = FileUtil.find(testDirectory, ".*FileUtil\\.java", true).get(0); + File testUtilFile = FileUtil.find(testDirectory, ".*fileUtilData\\.txt", true).get(0); - List<CharSequence> lines = FileUtil.grep("grep\\(String .*\\)", testUtilFile , "UTF-8"); + List<CharSequence> lines = FileUtil.grep("grep\\(String .*\\)", testUtilFile, "UTF-8"); Assert.assertEquals(4, lines.size()); - - lines = FileUtil.grep("sedfoo", testUtilFile , "UTF-8"); + + lines = FileUtil.grep("sedfoo", testUtilFile, "UTF-8"); Assert.assertNull(lines); // real method to test here : sed - FileUtil.sed("grep", "sedfoo", testUtilFile , "UTF-8"); + FileUtil.sed("grep", "sedfoo", testUtilFile, "UTF-8"); - lines = FileUtil.grep("grep\\(String .*\\)", testUtilFile , "UTF-8"); + lines = FileUtil.grep("grep\\(String .*\\)", testUtilFile, "UTF-8"); Assert.assertNull(lines); - lines = FileUtil.grep("sedfoo", testUtilFile , "UTF-8"); + lines = FileUtil.grep("sedfoo", testUtilFile, "UTF-8"); Assert.assertEquals(9, lines.size()); // clean FileUtil.deleteRecursively(testDirectory); } - + /** * Test sed on a multiple files. - * + * <p/> * Try to replace all "CodeLutin" by "nuiton" in all files. Can fail if some * src files are deleted. - * - * @throws IOException + * + * @throws IOException */ @Test public void testSedMultiple() throws IOException { @@ -239,28 +244,28 @@ File testDirectory = FileUtil.createTempDirectory("sed", "test"); FileUtil.copyRecursively(new File("src").getAbsoluteFile(), testDirectory); - Map<File, List<CharSequence>> results = FileUtil.grep("CodeLutin", testDirectory , ".*\\.java", "UTF-8"); - Assert.assertTrue("should have more than 50 files, but found : "+ + Map<File, List<CharSequence>> results = FileUtil.grep("CodeLutin", testDirectory, ".*\\.java", "UTF-8"); + Assert.assertTrue("should have more than 50 files, but found : " + results.size(), results.size() > 50); - FileUtil.sed("CodeLutin", "Nuiton", testDirectory, ".*\\.java" , "UTF-8"); + FileUtil.sed("CodeLutin", "Nuiton", testDirectory, ".*\\.java", "UTF-8"); - results = FileUtil.grep("CodeLutin", testDirectory , ".*\\.java", "UTF-8"); + results = FileUtil.grep("CodeLutin", testDirectory, ".*\\.java", "UTF-8"); Assert.assertTrue(results.isEmpty()); - results = FileUtil.grep("Nuiton", testDirectory , ".*\\.java", "UTF-8"); - Assert.assertTrue("should have more than 50 files, but found : "+ + results = FileUtil.grep("Nuiton", testDirectory, ".*\\.java", "UTF-8"); + Assert.assertTrue("should have more than 50 files, but found : " + results.size(), results.size() > 50); - + // clean FileUtil.deleteRecursively(testDirectory); } - + /** * Test that sed result which produce shorter file work as well. - * - * @throws IOException + * + * @throws IOException */ @Test public void testSedComment() throws IOException { @@ -268,16 +273,16 @@ // try to not make sed in real src dir ;) File testDirectory = FileUtil.createTempDirectory("sed", "test", parent); FileUtil.copyRecursively(new File("src").getAbsoluteFile(), testDirectory); - File testUtilFile = FileUtil.find(testDirectory, ".*FileUtil\\.java", true).get(0); + File testUtilFile = FileUtil.find(testDirectory, ".*fileUtilData\\.txt", true).get(0); // real method to test here : sed - FileUtil.sed(".*\\*.*", "** skipped **", testUtilFile , "UTF-8"); + FileUtil.sed(".*\\*.*", "** skipped **", testUtilFile, "UTF-8"); - List<CharSequence> lines = FileUtil.grep("/var/tmp/bidulle", testUtilFile , "UTF-8"); + List<CharSequence> lines = FileUtil.grep("/var/tmp/bidulle", testUtilFile, "UTF-8"); Assert.assertNull(lines); // test une presence en debut et fin de fichier - List<CharSequence> lines2 = FileUtil.grep("// FileUtil", testUtilFile , "UTF-8"); + List<CharSequence> lines2 = FileUtil.grep("// FileUtil", testUtilFile, "UTF-8"); Assert.assertEquals(2, lines2.size()); // clean @@ -288,7 +293,8 @@ @BeforeClass public static void beforeTest() { - parent = TestHelper.createTestsDataDirectory("FileUtil"); + parent = TestHelper.createTestsDataDirectory( + "surefire-workdir" + File.separator + "FileUtil"); } public void testChangeExtension() throws IOException { Modified: trunk/nuiton-utils/src/test/java/org/nuiton/util/ResourceTest.java =================================================================== --- trunk/nuiton-utils/src/test/java/org/nuiton/util/ResourceTest.java 2011-05-14 11:44:58 UTC (rev 2139) +++ trunk/nuiton-utils/src/test/java/org/nuiton/util/ResourceTest.java 2011-05-15 10:35:01 UTC (rev 2140) @@ -25,26 +25,32 @@ package org.nuiton.util; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Assert; +import org.junit.Test; + import java.io.File; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; -import org.junit.Assert; -import org.junit.Test; - /** * Test class for {@link Resource}. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ public class ResourceTest { // ResourceTest + /** Logger. */ + private static final Log log = LogFactory.getLog(ResourceTest.class); + @Test public void testaddDefaultClassLoader() throws Exception { Assert.assertNull(ResourceTest.class.getResource("/bin/java")); @@ -56,11 +62,11 @@ Assert.assertTrue(result.exists()); URL resultURL = Resource.getURL("bin/java"); - Assert.assertEquals(result.toURI().toURL(),resultURL); + Assert.assertEquals(result.toURI().toURL(), resultURL); } @Test - public void testGetURL()throws Exception { + public void testGetURL() throws Exception { URL url; url = Resource.getURL("README.txt"); @@ -99,15 +105,21 @@ @Test public void testGetURLs() throws Exception { - System.out.println(java.util.Arrays.asList(((URLClassLoader)ClassLoader.getSystemClassLoader()).getURLs())); + if (log.isInfoEnabled()) { + log.info(Arrays.asList(((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs())); + } List<URL> result; result = Resource.getURLs(".*bin/java"); - System.out.println(result); + if (log.isInfoEnabled()) { + log.info(result); + } result = Resource.getURLs("META-INF/MANIFEST.MF"); - System.out.println(result); + if (log.isInfoEnabled()) { + log.info(result); + } } @Test @@ -118,7 +130,7 @@ Assert.assertFalse(Resource.isJar("")); Assert.assertFalse(Resource.isJar(null)); } - + @Test public void testIsZip() throws Exception { Assert.assertTrue(Resource.isZip("toto.zip")); @@ -134,10 +146,10 @@ Assert.assertTrue(Resource.isPattern(".?.zip")); Assert.assertFalse(Resource.isPattern("toto.zip")); } - + /** * Test de recherche de resource dans le classpath (jar). - * + * * @throws Exception */ @Test @@ -148,7 +160,7 @@ List<URL> urlsClass2 = Resource.getResources("org/nuiton/util/VersionUtilTest.class"); Assert.assertEquals(2, urlsPattern.size()); Assert.assertEquals(urlsPattern.size(), urlsClass1.size() + urlsClass2.size()); - + // test sans dossier de recherche (directement un pattern) List<URL> urlsAllPattern = Resource.getResources("log4j\\..*"); Assert.assertEquals(1, urlsAllPattern.size()); @@ -156,7 +168,7 @@ /** * Test de recherche de resource dans le classpath (dossier hors jar). - * + * * @throws Exception */ @Test @@ -165,20 +177,37 @@ // i18n, resources, test resources Assert.assertEquals(3, urls.size()); } - + /** * Test de recherche de resource dans le classpath (dossier hors jar) en * utiliant le classloader de test. - * + * * @throws Exception */ @Test public void testGetTestResourcesClassPath() throws Exception { + URL url1; + URL url2; + url1 = getClass().getResource("/org/nuiton/util/fileUtilData.txt"); + url2 = getClass().getResource("/org/nuiton/util/reverseread.txt"); + List<URL> urls = Resource.getResources("org/nuiton/util/.*\\.txt"); - Assert.assertEquals(1, urls.size()); - + // there is at least two such files : fileUtilData.txt and + // reverseread.txt + Assert.assertTrue(urls.size() >= 2); + Assert.assertTrue(urls.contains(url1)); + Assert.assertTrue(urls.contains(url2)); + urls = Resource.getResources("org/nuiton/util/.*\\.txt", ResourceTest.class.getClassLoader()); - Assert.assertEquals(1, urls.size()); + + url1 = ResourceTest.class.getClassLoader().getResource("org/nuiton/util/fileUtilData.txt"); + url2 = ResourceTest.class.getClassLoader().getResource("org/nuiton/util/reverseread.txt"); + + // there is at least two such files : fileUtilData.txt and + // reverseread.txt + Assert.assertTrue(urls.size() >= 2); + Assert.assertTrue(urls.contains(url1)); + Assert.assertTrue(urls.contains(url2)); } } // ResourceTest Modified: trunk/nuiton-utils/src/test/java/org/nuiton/util/ZipUtilTest.java =================================================================== --- trunk/nuiton-utils/src/test/java/org/nuiton/util/ZipUtilTest.java 2011-05-14 11:44:58 UTC (rev 2139) +++ trunk/nuiton-utils/src/test/java/org/nuiton/util/ZipUtilTest.java 2011-05-15 10:35:01 UTC (rev 2140) @@ -73,7 +73,7 @@ File basedirFile = new File(basedir); testWorkDir = new File(basedirFile, "target" + File.separator + - "test-workdir"); + "surefire-workdir"); boolean b = testWorkDir.exists() || testWorkDir.mkdirs(); if (!b) { Added: trunk/nuiton-utils/src/test/resources/org/nuiton/util/fileUtilData.txt =================================================================== --- trunk/nuiton-utils/src/test/resources/org/nuiton/util/fileUtilData.txt (rev 0) +++ trunk/nuiton-utils/src/test/resources/org/nuiton/util/fileUtilData.txt 2011-05-15 10:35:01 UTC (rev 2140) @@ -0,0 +1,1421 @@ +/* + * #%L + * Nuiton Utils + * + * $Id$ + * $HeadURL: http://svn.nuiton.org/svn/nuiton-utils/trunk/nuiton-utils/src/main/java/org/... $ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +/* * + * FileUtil.java + * + * Created: 22 nov. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : */ + +package org.nuiton.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JFileChooser; +import java.awt.Component; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintStream; +import java.nio.CharBuffer; +import java.nio.MappedByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Opérations sur des fichiers. Copie, suppression, renommage, + * recherche, fichiers d'un répertoire, sous-répertoires d'un répertoire, + * récupération du basename ou de l'extension, création d'un fichier + * temporaire, comparaison de dates de création, récupération d'une chaîne, + * d'un Reader ou d'un Writer à partir d'un fichier, récupération du fichier + * saisi dans une boîte de dialogue, conversions en byte[], en Stream... + * <p/> + * Created: 22 novembre 2004 + * + * @author bpoussin <poussin@codelutin.com> + * $Id$ + */ +public class FileUtil { // FileUtil + + /** Logger. */ + static private Log log = LogFactory.getLog(FileUtil.class); + + /** Encoding utilisé (peut être redéfini) */ + // TODO fdesbois 2011-04-16 : Perhaps change ISO encoding by UTF-8 + static public String ENCODING = "ISO-8859-1"; + static protected File currentDirectory = new File("."); + + static public void setCurrentDirectory(File dir) { + currentDirectory = dir; + } + + static public File getCurrentDirectory() { + return currentDirectory; + } + + static public class PatternChooserFilter extends javax.swing.filechooser.FileFilter { + protected String pattern; + protected String description; + + public PatternChooserFilter(String pattern, String description) { + this.pattern = pattern; + this.description = description; + } + + @Override + public boolean accept(File f) { + return f.isDirectory() || f.getAbsolutePath().matches(pattern); + } + + @Override + public String getDescription() { + return description; + } + + } + + + /** + * Retourne le nom du fichier entre dans la boite de dialogue. + * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. + * + * @param patternOrDescriptionFilters les filtres a utiliser, les chaines doivent etre données + * par deux, le pattern du filtre + la description du filtre + * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé + * @see #getFile(javax.swing.filechooser.FileFilter...) + */ + static public File getFile(String... patternOrDescriptionFilters) { + File result; + result = getFile(null, patternOrDescriptionFilters); + return result; + } + + /** + * Retourne le nom du fichier entre dans la boite de dialogue. + * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. + * + * @param filters les filtres a ajouter + * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé + */ + static public File getFile(javax.swing.filechooser.FileFilter... filters) { + File result = getFile(null, filters); + return result; + } + + /** + * Retourne le nom du fichier entre dans la boite de dialogue. + * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. + * + * @param parent le component parent du dialog + * @param patternOrDescriptionFilters les filtres a utiliser, les chaines doivent etre données + * par deux, le pattern du filtre + la description du filtre + * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé + * @see #getFile(javax.swing.filechooser.FileFilter...) + */ + static public File getFile(Component parent, + String... patternOrDescriptionFilters) { + File result; + result = getFile("Ok", "Ok", parent, patternOrDescriptionFilters); + return result; + } + + /** + * Retourne le nom du fichier entre dans la boite de dialogue. + * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. + * + * @param title le titre de la boite de dialogue + * @param approvalText le label du boutton d'acceptation + * @param parent le component parent du dialog + * @param patternOrDescriptionFilters les filtres a utiliser, les chaines doivent etre données + * par deux, le pattern du filtre + la description du filtre + * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé + * @see #getFile(javax.swing.filechooser.FileFilter...) + */ + static public File getFile(String title, + String approvalText, + Component parent, + String... patternOrDescriptionFilters) { + + if (patternOrDescriptionFilters.length % 2 != 0) { + throw new IllegalArgumentException("Arguments must be (pattern, description) couple"); + } + javax.swing.filechooser.FileFilter[] filters = + new javax.swing.filechooser.FileFilter[patternOrDescriptionFilters.length / 2]; + for (int i = 0; i < filters.length; i++) { + String pattern = patternOrDescriptionFilters[i * 2]; + String description = patternOrDescriptionFilters[i * 2 + 1]; + filters[i] = new PatternChooserFilter(pattern, description); + } + File result; + result = getFile(title, approvalText, parent, filters); + return result; + } + + + /** + * Retourne le nom du fichier entre dans la boite de dialogue. + * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. + * + * @param parent le component parent du dialog + * @param filters les filtres a ajouter + * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé + */ + static public File getFile(Component parent, + javax.swing.filechooser.FileFilter... filters) { + File result = getFile("Ok", "Ok", parent, filters); + return result; + } + + /** + * Retourne le nom du fichier entre dans la boite de dialogue. + * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne null. + * + * @param title le titre de la boite de dialogue + * @param approvalText le label du boutton d'acceptation + * @param parent le component parent du dialog + * @param filters les filtres a ajouter + * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé + */ + static public File getFile(String title, + String approvalText, + Component parent, + javax.swing.filechooser.FileFilter... filters) { + try { + JFileChooser chooser = new JFileChooser(currentDirectory); + + chooser.setDialogType(JFileChooser.CUSTOM_DIALOG); + if (filters.length > 0) { + if (filters.length == 1) { + chooser.setFileFilter(filters[0]); + } else { + for (javax.swing.filechooser.FileFilter filter : filters) { + chooser.addChoosableFileFilter(filter); + } + } + } + chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + chooser.setDialogTitle(title); + int returnVal = chooser.showDialog(parent, approvalText); + if (returnVal == JFileChooser.APPROVE_OPTION) { + File theFile = chooser.getSelectedFile(); + if (theFile != null) { + currentDirectory = theFile; + return theFile.getAbsoluteFile(); + } + } + } + catch (Exception eee) { + log.warn("Erreur:", eee); + } + return null; + } + + /** + * @return le nom du repertoire entre dans la boite de dialogue. + * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne + * null. + */ + static public String getDirectory() { + return getDirectory(null,"Ok", "Ok"); + } + + /** + * @param title le nom de la boite de dialogue + * @param approvalText le texte de l'action d'acceptation du répertoire dans le file chooser + * @return le nom du repertoire entre dans la boite de dialogue. + * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne + * null. + */ + static public String getDirectory(String title, String approvalText) { + String result = getDirectory(null, title, approvalText); + return result; + } + + /** + * @param parent le component parent du dialog + * @param title le nom de la boite de dialogue + * @param approvalText le texte de l'action d'acceptation du répertoire dans le file chooser + * @return le nom du repertoire entre dans la boite de dialogue. + * Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne + * null. + */ + static public String getDirectory(Component parent, + String title, + String approvalText) { + try { + JFileChooser chooser = new JFileChooser(currentDirectory); + chooser.setDialogType(JFileChooser.CUSTOM_DIALOG); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + chooser.setDialogTitle(title); + int returnVal = chooser.showDialog(parent, approvalText); + if (returnVal == JFileChooser.APPROVE_OPTION) { + File theFile = chooser.getSelectedFile(); + if (theFile != null) { + currentDirectory = theFile; + if (theFile.isDirectory()) { + return theFile.getAbsolutePath(); + } + } + } else { + return null; + } + } catch (Exception eee) { + log.warn("Erreur:", eee); + } + return null; + } + + /** + * Permet de convertir un fichier en un tableau de byte + * + * @param file le fichier source à convertire + * @return le contenu du fichier sous la forme d'un tableau de bytes. + * @throws IOException if any io pb + */ + static public byte[] fileToByte(File file) throws IOException { + ByteArrayOutputStream result; + InputStream in = new BufferedInputStream(new FileInputStream(file)); + try { + result = new ByteArrayOutputStream(); + BufferedOutputStream tmp = new BufferedOutputStream(result); + try { + for (int b = in.read(); b != -1; b = in.read()) { + tmp.write(b); + } + } finally { + tmp.close(); + } + } finally { + in.close(); + } + return result.toByteArray(); + } + + /** + * Permet de recopier un stream dans un fichier + * + * @param src the incoming stream to grab + * @param dst the dst file + * @return the file filled by incoming input stream + * @throws IOException if any io pb + * @throws NullPointerException if src or dst parameter is null + */ + static public File inputStreamToFile(InputStream src, File dst) throws IOException, NullPointerException { + if (src == null) { + throw new NullPointerException("parameter 'src' can not be null"); + } + if (dst == null) { + throw new NullPointerException("parameter 'dst' can not be null"); + } + + ByteArrayOutputStream result = new ByteArrayOutputStream(); + BufferedOutputStream tmp = new BufferedOutputStream(result); + try { + for (int b = src.read(); b != -1; b = src.read()) { + tmp.write(b); + } + src.close(); + } finally { + tmp.close(); + } + byteToFile(result.toByteArray(), dst); + return dst; + } + + /** + * Permet de convertir des bytes en fichier, le fichier sera automatiquement + * supprimé a la fin de la JVM. + * + * @param bytes the array of bytes to copy in dstination file + * @return le fichier temporaire contenant les bytes + * @throws IOException if any io pb + */ + static public File byteToFile(byte[] bytes) throws IOException { + File file = File.createTempFile("FileUtil-byteToFile", ".tmp"); + byteToFile(bytes, file); + return file; + } + + /** + * Permet de convertir des bytes en fichier + * + * @param bytes the array of bytes to put in the given destination file + * @param file le fichier dans lequel il faut ecrire les bytes + * @return le fichier passé en parametre + * @throws IOException if any io pb + */ + static public File byteToFile(byte[] bytes, + File file) throws IOException { + OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); + try { + out.write(bytes); + } finally { + out.close(); + } + return file; + } + + /** + * Retourne un Reader utilisant l'encoding par defaut {@link #ENCODING}. + * + * @param file the given reader + * @return the reader on the given file + * @throws IOException if any io pb + */ + static public BufferedReader getReader(File file) throws IOException { + return getReader(file, ENCODING); + } + + /** + * Retourne un reader utilisant l'encoding choisi et placé dans un + * BufferedReader + * + * @param file the given file + * @param encoding (ISO-8859-1, UTF-8, ...) + * @return the buffered reader in the given encoding + * @throws IOException if any io pb + */ + static public BufferedReader getReader(File file, + String encoding) throws IOException { + FileInputStream inf = new FileInputStream(file); + InputStreamReader in = new InputStreamReader(inf, encoding); + BufferedReader result = new BufferedReader(in); + return result; + } + + /** + * Retourne un Writer utilisant l'encoding par defaut {@link #ENCODING}. + * + * @param file the given file + * @return the writer on the given file + * @throws IOException if any io pb + */ + static public BufferedWriter getWriter(File file) throws IOException { + return getWriter(file, ENCODING); + } + + /** + * Retourne un writer utilisant l'encoding choisi et placé dans un + * BufferedWriter + * + * @param file the given file + * @param encoding (ISO-8859-1, UTF-8, ...) + * @return the buffered writer on the given file with given encoding + * @throws IOException if any io pb + */ + static public BufferedWriter getWriter(File file, + String encoding) throws IOException { + FileOutputStream outf = new FileOutputStream(file); + OutputStreamWriter out = new OutputStreamWriter(outf, encoding); + BufferedWriter result = new BufferedWriter(out); + return result; + } + + + /** + * Permet de creer un nouveu repertoire temporaire, l'effacement du + * répertoire est a la charge de l'appelant + * + * @param prefix le prefix du fichier + * @param suffix le suffix du fichier + * @param tmpdir le répertoire temporaire ou il faut creer le repertoire + * si null on utilise java.io.tmpdir + * @return le fichier pointant sur le nouveau repertoire + * @throws IOException if any io pb + */ + static public File createTempDirectory(String prefix, + String suffix, + File tmpdir) throws IOException { + if (tmpdir == null) { + tmpdir = new File(System.getProperty("java.io.tmpdir")); + } + File result = new File(tmpdir, prefix + System.currentTimeMillis() + suffix); + while (result.exists()) { + result = new File(tmpdir, prefix + System.currentTimeMillis() + suffix); + } + if (!result.mkdirs()) { + throw new IOException("Can't create temporary directory: " + result); + } + return result; + } + + /** + * Permet de creer un nouveu repertoire temporaire, l'effacement du + * répertoire est a la charge de l'appelant + * + * @param prefix le prefix du repertoire a creer + * @param suffix le suffix du repertoire a creer. + * @return the temprary created file + * @throws IOException if any io pb + */ + static public File createTempDirectory(String prefix, + String suffix) throws IOException { + return createTempDirectory(prefix, suffix, null); + } + + /** + * Regarde si le fichier f1 est plus recent que le fichier f2 + * + * @param f1 the first file + * @param f2 the second file + * @return vrai si f1 est plus recent que f2 + */ + static public boolean isNewer(File f1, File f2) { + boolean result = f1.lastModified() > f2.lastModified(); + return result; + } + + /** + * Permet de lire un fichier et de retourner sont contenu sous forme d'une + * chaine de carateres + * + * @param file le fichier a lire + * @return le contenu du fichier + * @throws IOException if any io pb + */ + static public String readAsString(File file) throws IOException { + StringBuffer result = new StringBuffer(); + char[] cbuf = new char[2000]; + BufferedReader in = getReader(file); + int nb = in.read(cbuf); + while (nb != -1) { + result.append(cbuf, 0, nb); + nb = in.read(cbuf); + } + in.close(); + return result.toString(); + } + + /** + * Permet de sauver une chaine directement dans un fichier + * + * Use default enconding : {@link #ENCODING}. + * + * @param file Le fichier dans lequel il faut ecrire la chaine + * @param content Le texte a ecrire dans le fichier + * @throws IOException if any pb while writing + */ + static public void writeString(File file, + String content) throws IOException { + //fixme on doit tester le retour de la méthode, car il se peut que le répertoire + // ne puisse etre cree. + File parentFile = file.getParentFile(); + //TODO tchemit 2011-05-15 Must test if directory was created (use + // the #createDirectoryIfNecessary method). + if (parentFile != null) { + parentFile.mkdirs(); + } + + BufferedWriter out = getWriter(file); + out.write(content); + out.close(); + } + + /** + * Permet de sauver une chaine directement dans un fichier + * + * @param file Le fichier dans lequel il faut ecrire la chaine + * @param content Le texte a ecrire dans le fichier + * @param encoding encoding to use + * @throws IOException if any pb while writing + */ + static public void writeString(File file, + String content, + String encoding) throws IOException { + //fixme on doit tester le retour de la méthode, car il se peut que le répertoire + // ne puisse être crée. + File parentFile = file.getParentFile(); + //TODO tchemit 2011-05-15 Must test if directory was created (use + // the #createDirectoryIfNecessary method). + if (parentFile != null) { + parentFile.mkdirs(); + } + + BufferedWriter out = getWriter(file, encoding); + out.write(content); + out.close(); + } + + /** + * Permet de donner une representation fichier pour une chaine de caractere. + * Le fichier sera automatiquement effacé à la fin de la JVM. + * + * @param content le contenu du fichier temporaire + * @return le fichier qui contient content + * @throws IOException if any io pb + */ + static public File getTempFile(String content) throws IOException { + return getTempFile(content, ""); + } + + /** + * Permet de donner une representation fichier pour une chaine de caractere. + * Le fichier sera automatiquement effacé à la fin de la JVM. + * + * @param content le contenu du fichier temporaire + * @param fileSuffix l'extension du fichier créé + * @return le fichier qui contient content + * @throws IOException if any io pb + */ + static public File getTempFile(String content, + String fileSuffix) throws IOException { + File result = File.createTempFile("tmp-" + FileUtil.class.getName(), + fileSuffix); + result.deleteOnExit(); + writeString(result, content); + return result; + } + + /** + * Equivalent de la methode basename unix. + * basename("/tmp/toto.xml", ".xml") -> "toto" + * + * @param file le fichier dont on souhaite le nom sans le chemin + * @param suffixes si present represente le suffixe a eliminer du fichier + * s'il est trouvé + * @return le nom du fichier sans le suffixe si trouvé. + */ + static public String basename(File file, String... suffixes) { + String result = basename(file.getName(), suffixes); + return result; + } + + /** + * Equivalent de la methode basename unix. + * basename("/tmp/toto.xml", ".xml") -> "toto" + * + * @param name le nom du fichier dont on souhaite le nom sans le chemin + * @param suffixes si present represente le suffixe a eliminer du fichier + * s'il est trouvé + * @return le nom du fichier sans le suffixe si trouvé. + * @since 1.4.2 + */ + static public String basename(String name, String... suffixes) { + String result = name; + for (String suffixe : suffixes) { + if (result.endsWith(suffixe)) { + result = result.substring(0, + result.length() - suffixe.length()); + break; + } + } + return result; + } + + /** + * Permet de récupérer l'extension d'un fichier + * + * @param file le fichier dont on souhaite l'extension + * @param extchars la liste des caracteres pouvant former l'extension + * dans l'ordre de preference. Si vide on utilise ".". + * @return l'extension ou la chaine vide si le fichier n'a pas d'extension + * l'extension ne contient pas le chaine de delimitation + */ + static public String extension(File file, String... extchars) { + String name = file.getName(); + String result = extension(name, extchars); + return result; + } + + /** + * Permet de récupérer l'extension d'un nom de fichier + * + * @param name le nom du fichier dont on souhaite l'extension + * @param extchars la liste des caracteres pouvant former l'extension + * dans l'ordre de preference. Si vide on utilise ".". + * @return l'extension ou la chaine vide si le fichier n'a pas d'extension + * l'extension ne contient pas le chaine de delimitation + * @since 1.4.2 + */ + static public String extension(String name, String... extchars) { + String result = ""; + + if (extchars.length == 0) { + extchars = new String[]{"."}; + } + for (String extchar : extchars) { + int pos = name.lastIndexOf(extchar); + if (pos != -1) { + result = name.substring(pos + extchar.length()); + break; + } + } + return result; + } + + /** + * Recupère le fichier dans le même répertoire que le fichier donné et dont + * on a changé l'extension. + * + * @param file le fichier d'origine + * @param newExtension la nouvelle extension à utiliser + * @param extchars la liste des extensions possibles + * @return le fichier dont on a changé l'extension + * @throws IOException si aucune extension trouvé dans le fichier d'origine + * @since 1.4.2 + */ + static public File changeExtension(File file, + String newExtension, + String... extchars) throws IOException { + String name = file.getName(); + String newName = changeExtension(name, newExtension, extchars); + File newFile = new File(file.getParentFile(), newName); + return newFile; + } + + /** + * Change l'extension du fichier en entrée avec la nouvelle extension + * + * @param name le nom de fichier à transformer + * @param newExtension la nouvelle extension à utiliser + * @param extchars la liste des extensions possibles + * @return le nouveau nom de fichier + * @throws IOException si aucune extension trouvé dans le fichier d'origine + * @since 1.4.2 + */ + static public String changeExtension(String name, + String newExtension, + String... extchars) throws IOException { + String extension = extension(name, extchars); + if (extension == null) { + throw new IOException("Could not find extension for name " + + name + " within " + Arrays.toString(extchars)); + } + String nameWithoutExtension = name.substring( + 0, name.length() - extension.length()); + String newName = nameWithoutExtension + newExtension; + return newName; + } + + /** + * Recupère le fichier mirroir du fichier {@code file} donnée qui est dans + * l'arborescence de {@code inputDirectory} dans le répertoire + * {@code ouputDirectory}. + * + * @param inputDirectory le répertoire de départ + * @param outputDirectory le répertoire cible + * @param file le fichier + * @return le fichier mirroir dans le répertoire cible + * @since 1.4.2 + */ + static public File getRelativeFile(File inputDirectory, + File outputDirectory, + File file) { + String inputPath = inputDirectory.getAbsolutePath(); + String s = file.getAbsolutePath(); + int index = s.indexOf(inputPath); + if (index == -1) { + throw new IllegalArgumentException( + "File " + file + " is not in " + inputDirectory); + } + String relativePath = s.substring(inputPath.length()); + File result = new File(outputDirectory, relativePath); + return result; + } + + public interface FileAction { + boolean doAction(File f); + } + + /** + * Retourne tous les sous répertoires du répertoire passé en argument. + * + * @param directory un répertoire + * @return une liste d'objet {@link File} de répertoires et ceci + * recursivement à partir de directory, si directory + * n'est pas un répertoire la liste est vide. + */ + public static List<File> getSubDirectories(File directory) { + class DirectoryFilter implements FileFilter { + @Override + public boolean accept(File f) { + return f.isDirectory(); + } + } + return getFilteredElements(directory, new DirectoryFilter(), true); + } + + /** + * Retourne tous les fichiers du répertoire passé en argument. + * + * @param directory un répertoire + * @return une liste d'objet {@link File} des fichiers et ceci + * recursivement à partir de directory, si directory n'est pas un + * répertoire la liste est vide + */ + public static List<File> getFiles(File directory) { + class NormalFileFilter implements FileFilter { + @Override + public boolean accept(File f) { + return f.isFile(); + } + } + return getFilteredElements(directory, new NormalFileFilter(), true); + } + + /** + * Retourne les fichiers d'un répertoire qui satisfont un certain pattern. + * La recherche est faite récursivement dans les sous répertoires + * + * @param directory le répertoire à partir duquel il faut faire la recherche + * @param pattern le pattern que doit respecter le fichier pour être dans la + * liste résultante + * @param recursively flag pour indiquer si on doit descendre dans les sous répertoires + * @return une liste d'objet {@link File} qui ont s'attisfait le + * pattern. + */ + public static List<File> find(File directory, + final String pattern, + boolean recursively) { + final String root = directory.getAbsolutePath(); + final int rootLength = root.length(); + + return getFilteredElements(directory, new FileFilter() { + @Override + public boolean accept(File f) { + String longFilename = f.getAbsolutePath(); + // + 1 to remove the first / or \ + String filename = longFilename.substring(rootLength + 1); + return filename.matches(pattern); + } + }, recursively); + } + + /** + * Retourne la liste de toutes les fichiers ou répertoire qui s'attisfont + * le filtre + * + * @param directory repertoire à partir duquel il faut faire la recherche + * @param ff le filtre à appliquer pour savoir si le fichier parcouru doit + * être conservé dans les résultats, ou null pour tous les fichiers + * @param recursively un flag pour indiquer si on doit descendre dans les répertoires + * @return une liste d'objet {@link File}, qui s'attisfont le filtre + */ + public static List<File> getFilteredElements(File directory, + FileFilter ff, + boolean recursively) { + ArrayList<File> result = new ArrayList<File>(); + LinkedList<File> todo = new LinkedList<File>(); + if (directory.isDirectory()) { + todo.addAll(Arrays.asList(directory.listFiles())); + } + while (todo.size() > 0) { + File file = todo.removeFirst(); + if (recursively && file.isDirectory()) { + File[] childs = file.listFiles(); + if (childs != null) { + // null if we don't have access to directory + todo.addAll(Arrays.asList(childs)); + } + } + if (ff == null || ff.accept(file)) { + result.add(file); + } + } + return result; + } + + /** + * Supprime recursivement tout le contenu d'un répertoire. + * + * @param directory le chemin du répertoire à supprimer + * @return vrai si tout se passe bien, false si la suppression d'un élement + * se passe mal + */ + public static boolean deleteRecursively(String directory) { + return deleteRecursively(new File(directory)); + } + + /** + * Supprime recursivement tout le contenu d'un répertoire. + * + * @param directory le répertoire à supprimer + * @return vrai si tout se passe bien, false si la suppression d'un élement + * se passe mal + */ + public static boolean deleteRecursively(File directory) { + return walkBefore(directory, new FileAction() { + @Override + public boolean doAction(File f) { + return f.delete(); + } + }); + } + + /** + * Permet de faire une action avant le parcours des fichiers, c-a-d que + * l'on fera l'action sur les fichiers contenu dans un répertoire + * après l'action sur le répertoire lui même. + * + * @param f le fichier ou répertoire à partir duquel il faut commencer + * @param fileAction l'action à effectuer sur chaque fichier + * @return le résultat des fileAction executé sur les fichiers, chaque + * résultat de FileAction sont assemblé par un ET logique pour donner + * le résultat final + */ + public static boolean walkAfter(File f, FileAction fileAction) { + boolean result = fileAction.doAction(f); + if (f.isDirectory()) { + File list[] = f.listFiles(); + for (File aList : list) { + result = result && walkAfter(aList, fileAction); + } + } + return result; + } + + /** + * Permet de faire une action apès le parcours des fichiers, c-a-d que + * l'on fera l'action sur les fichiers contenu dans un répertoire + * avant l'action sur le répertoire lui même. + * + * @param f le fichier ou répertoire à partir duquel il faut commencer + * @param fileAction l'action à effectuer sur chaque fichier + * @return le résultat des fileAction executé sur les fichiers, chaque + * résultat de FileAction sont assemblé par un ET logique pour donner + * le résultat final + */ + public static boolean walkBefore(File f, FileAction fileAction) { + boolean result = true; + if (f.isDirectory()) { + File list[] = f.listFiles(); + for (File aList : list) { + result = result && walkBefore(aList, fileAction); + } + } + return result && fileAction.doAction(f); + } + + /** + * Permet de copier le fichier source vers le fichier cible. + * + * @param source le fichier source + * @param target le fichier cible + * @throws IOException Erreur de copie + */ + public static void copy(File source, File target) throws IOException { + //fixme on doit tester le retour de la méthode, car il se peut que le répertoire + // ne puisse être copié. + //TODO tchemit 2011-05-15 Must test if directory was created (use + // the #createDirectoryIfNecessary method). + target.getParentFile().mkdirs(); + FileInputStream fileInputStream = new FileInputStream(source); + try { + FileChannel sourceChannel = fileInputStream.getChannel(); + FileOutputStream fileOutputStream = new FileOutputStream(target); + try { + FileChannel targetChannel = fileOutputStream.getChannel(); + sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); + // or + // targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); + targetChannel.close(); + } finally { + fileOutputStream.close(); + } + sourceChannel.close(); + } finally { + fileInputStream.close(); + } + } + + /** + * Permet de copier le fichier source vers le fichier cible. + * + * @param source le fichier source + * @param target le fichier cible + * @throws IOException Erreur de copie + */ + public static void copy(String source, String target) throws IOException { + copy(new File(source), new File(target)); + } + + /** + * Copie recursivement le repertoire source dans le repertoire destination + * <p/> + * copyRecursively("/truc/titi", "/var/tmp") donnera le repertoire + * "/var/tmp/titi" + * + * @param srcDir le répertoire source à copier + * @param destDir le répertoire destination où copier + * @param includePatterns les patterns que doivent resperter les + * fichiers/repertoires pour etre copié. Si vide alors tout est copié + * @throws IOException if any io pb + */ + static public void copyRecursively(File srcDir, + File destDir, + String... includePatterns) throws IOException { + copyAndRenameRecursively(srcDir, destDir, null, null, includePatterns); + } + + /** + * Copie recursivement le repertoire source dans le repertoire destination + * <p/> + * copyRecursively("/truc/titi", "/var/tmp", "bidulle") donnera le repertoire + * "/var/tmp/bidulle", 'bidulle' remplacant 'titi' + * + * @param srcDir le répertoire source à copier + * @param destDir le répertoire destination où copier + * @param renameFrom pattern to permit rename file before uncompress it + * @param renameTo new name for file if renameFrom is applicable to it + * you can use $1, $2, ... if you have '(' ')' in renameFrom + * @param includePatterns les patterns que doivent resperter les + * fichiers/repertoires pour etre copié. Si vide alors tout est copié + * @throws IOException if any io pb + */ + static public void copyAndRenameRecursively(File srcDir, File destDir, + String renameFrom, + String renameTo, + String... includePatterns) throws IOException { + copyAndRenameRecursively(srcDir, + destDir, + true, + renameFrom, + renameTo, + false, + includePatterns + ); + } + + /** + * Copie recursivement le repertoire source dans le repertoire destination + * <p/> + * copyRecursively("/truc/titi", "/var/tmp", "bidulle") donnera le repertoire + * "/var/tmp/bidulle", 'bidulle' remplacant 'titi' + * + * @param srcDir le répertoire source à copier + * @param destDir le répertoire destination où copier + * @param includeSrcDir si vrai alors le repertoire source est copie dans le + * repertoire destination et non pas seulement les fichiers qu'il contient + * @param renameFrom pattern to permit rename file before uncompress it + * @param renameTo new name for file if renameFrom is applicable to it + * you can use $1, $2, ... if you have '(' ')' in renameFrom + * @param exclude inverse include pattern interpretation + * @param includePatterns les patterns que doivent resperter les + * fichiers/repertoires pour etre copié. Si vide alors tout est copié + * @throws IOException if any io pb + */ + static public void copyAndRenameRecursively(File srcDir, + File destDir, + boolean includeSrcDir, + String renameFrom, + String renameTo, + boolean exclude, + String... includePatterns) throws IOException { + String rootSrc; + if (includeSrcDir) { + rootSrc = srcDir.getParent(); + } else { + rootSrc = srcDir.getPath(); + } + List<File> files = getFilteredElements(srcDir, null, true); + log.debug("copyRecursively: " + files); + for (File file : files) { + boolean doCopy = copyRecursivelyAccept(file, includePatterns); + if (exclude ^ doCopy) { + String path = file.getPath().substring(rootSrc.length()); + if (renameFrom != null && renameTo != null) { + String tmp = path.replaceAll(renameFrom, renameTo); + if (log.isDebugEnabled()) { + log.debug("rename " + path + " -> " + tmp); + } + path = tmp; + } + + File destFile = new File(destDir, path); + if (file.isDirectory()) { + log.debug("create directory: " + destFile); + //fixme on doit tester le retour de la méthode, car il se peut que le répertoire + // ne puisse être copié. + destFile.mkdirs(); + } else { + log.debug("copy " + path + " to " + destFile); + copy(file, destFile); + } + } + } + } + + /** + * Get a ByteArrayOutputStream containing all data that could be read from the given InputStream + * @param inputStream the stream to read + * @param defaultBufferSize the buffer size + * @return the input stream read for input + * @throws IOException if any pb while reading or writing + */ + public static ByteArrayOutputStream readBytesFrom(InputStream inputStream, + int defaultBufferSize) throws IOException { + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream( + defaultBufferSize); + byte[] buffer = new byte[defaultBufferSize]; + + int readBytes = inputStream.read(buffer); + while (readBytes > 0) { + outputStream.write(buffer, 0, readBytes); + readBytes = inputStream.read(buffer); + } + + return outputStream; + } + + /** + * @param file le fichier à tester. + * @param includePatterns les patterns pour accepeter le fichier depuis son nom + * @return <code>true</code> si le fichier est accepté, <code>false> autrement. + */ + private static boolean copyRecursivelyAccept(File file, + String[] includePatterns) { + boolean result = includePatterns.length == 0; + String filename = file.getAbsolutePath(); + for (String pattern : includePatterns) { + result = filename.matches(pattern); + if (result) { + break; + } + } + return result; + } + + /** + * Use the linePattern to break the given CharBuffer into lines, applying + * the input pattern to each line to see if we have a match + * + * Code taken from : + * + * http://java.sun.com/javase/6/docs/technotes/guides/io/example/Grep.java + * + * @param regex regex to search into file + * @param cb nio buffer + * @return matching lines (or {code null} if no matching lines) + * @throws IOException + * @since 1.1.2 + */ + protected static List<CharSequence> grep(String regex, CharBuffer cb) { + + List<CharSequence> linesList = null; + + Pattern pattern = Pattern.compile(regex); + + Pattern linePattern = Pattern.compile(".*\r?\n"); + + Matcher lm = linePattern.matcher(cb); // Line matcher + Matcher pm = null; // Pattern matcher + //int lines = 0; + while (lm.find()) { + //lines++; + CharSequence cs = lm.group(); // The current line + if (pm == null) { + pm = pattern.matcher(cs); + } + else { + pm.reset(cs); + } + if (pm.find()) { + // init + if (linesList == null) { + linesList = new ArrayList<CharSequence>(); + } + linesList.add(cs); + } + if (lm.end() == cb.limit()) { + break; + } + } + + return linesList; + } + + /** + * Java implementation for the unix grep command. + * + * Code taken from : + * + * http://java.sun.com/javase/6/docs/technotes/guides/io/example/Grep.java + * + * @param searchRegex regex to search into file + * @param f file to search into + * @param encoding encoding to use + * @return matching lines (or {code null} if no matching lines) + * @throws IOException + * @since 1.1.2 + */ + public static List<CharSequence> grep(String searchRegex, File f, String encoding) throws IOException { + + List<CharSequence> lines = null; + + FileInputStream fis = null; + FileChannel fc = null; + + try { + // Open the file and then get a channel from the stream + fis = new FileInputStream(f); + fc = fis.getChannel(); + + // Get the file's size and then map it into memory + int sz = (int)fc.size(); + MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); + + // Decode the file into a char buffer + Charset charset = Charset.forName(encoding); + CharsetDecoder decoder = charset.newDecoder(); + CharBuffer cb = decoder.decode(bb); + + // Perform the search + lines = grep(searchRegex, cb); + } + finally { + // Close the channel and the stream + if (fc != null) { + fc.close(); + } + if (fis != null) { + fis.close(); + } + } + + return lines; + } + + /** + * Java implementation for the unix grep command. + * + * @param searchRegex regex to search into file + * @param rootDirectory directory to seacrh into + * @param fileRegex regex for file to find in {@code rootDirectory} + * @param encoding encoding to use + * @return all matching lines for each files + * @throws IOException + * @since 1.1.2 + */ + public static Map<File, List<CharSequence>> grep(String searchRegex, File rootDirectory, String fileRegex, String encoding) throws IOException { + Map<File, List<CharSequence>> results = + new HashMap<File, List<CharSequence>>(); + List<File> files = find(rootDirectory, fileRegex, true); + for (File file : files) { + List<CharSequence> lines = grep(searchRegex, file, encoding); + if (lines != null) { + results.put(file, lines); + } + } + return results; + } + + /** + * Search for files matching regex in current directory. + * + * @param searchRegex regex to search into file + * @param fileRegex regex for file to find in current dir + * @param encoding encoding to use + * @return all matching lines for each files + * @throws IOException + * @since 1.1.2 + */ + public static Map<File, List<CharSequence>> grep(String searchRegex, String fileRegex, String encoding) throws IOException { + Map<File, List<CharSequence>> results = grep(searchRegex, + new File("."), + fileRegex, + encoding); + return results; + } + + /** + * Sed implementation for a single file. + * + * Oginal source code from http://kickjava.com/src/org/apache/lenya/util/SED.java.htm. + * + * @param searchRegex Prefix which shall be replaced + * @param replace Prefix which is going to replace the original + * @param file File which sed shall be applied + * @param encoding charset encoding + * @throws IOException + * @since 1.1.2 + */ + public static void sed(String searchRegex, + String replace, + File file, + String encoding) throws IOException { + + Pattern pattern = Pattern.compile(searchRegex); + + String outString = null; + FileInputStream fis = new FileInputStream(file); + try { + // Open the file and then get a channel from the stream + FileChannel fc = fis.getChannel(); + + // Get the file's size and then map it into memory + int sz = (int)fc.size(); + MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); + + // Decode the file into a char buffer + // Charset and decoder for encoding + Charset charset = Charset.forName(encoding); + CharsetDecoder decoder = charset.newDecoder(); + CharBuffer cb = decoder.decode(bb); + + Matcher matcher = pattern.matcher(cb); + outString = matcher.replaceAll(replace); + } finally { + fis.close(); + } + + if (outString != null) { + PrintStream ps = new PrintStream(new FileOutputStream(file)); + try { + ps.print(outString); + } finally { + ps.close(); + } + } + } + + /** + * Java implementation for the unix sed command. + * + * @param searchRegex regex to search into file + * @param replace string to replace matching patterns + * @param rootDirectory directory to search into + * @param fileRegex regex for file to find in {@code rootDirectory} + * @param encoding encoding to use + * @throws IOException + * @since 1.1.2 + */ + public static void sed(String searchRegex, + String replace, + File rootDirectory, + String fileRegex, + String encoding) throws IOException { + List<File> files = find(rootDirectory, fileRegex, true); + for (File file : files) { + sed(searchRegex, replace, file, encoding); + } + } + + /** + * Java implementation for the unix sed command. + * + * @param searchRegex regex to search into file + * @param replace string to replace matching patterns + * @param fileRegex regex for file to find in current dir + * @param encoding encoding to use + * @throws IOException + * @since 1.1.2 + */ + public static void sed(String searchRegex, + String replace, + String fileRegex, + String encoding) throws IOException { + sed(searchRegex, replace, new File("."), fileRegex, encoding); + } + + /** + * Create the directory (and his parents) if necessary. + * + * @param dir the directory to create if not exisiting + * @return {@code true} if directory was created, {@code false} if was no + * need to create it + * @throws IOException if could not create directory + * @since 1.3.2 + */ + public static boolean createDirectoryIfNecessary(File dir) + throws IOException { + if (!dir.exists()) { + boolean b = dir.mkdirs(); + if (!b) { + throw new IOException("Could not create directory " + dir); + } + return true; + } + return false; + } + + /** + * Obtain a file from the given {@code rootDirectory}, applying given paths. + * <p/> + * For example with paths = a, b and c, then result is : + * <pre> + * root/a/b/c + * </pre> + * + * @param rootDirectory the root directory + * @param paths paths to apply + * @return the final file + * @since 2.2 + */ + public static File getFileFromPaths(File rootDirectory, String... paths) { + File result = rootDirectory; + for (String path : paths) { + result = new File(result, path); + } + return result; + } + + /** + * Obtain a file fro the given {@code rootDirectory}, applying the fqn. + * <p/> + * For example with fqn = a.b.c, the result is : + * <pre> + * root/a/b/c + * </pre> + * + * @param rootDirectory the root directory + * @param fqn fqn of searched file + * @return the final file + * @since 2.2 + */ + public static File getFileFromFQN(File rootDirectory, String fqn) { + String[] paths = fqn.split("\\."); + + File result = getFileFromPaths(rootDirectory, paths); + return result; + } + +} // FileUtil Property changes on: trunk/nuiton-utils/src/test/resources/org/nuiton/util/fileUtilData.txt ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision Added: svn:eol-style + native
participants (1)
-
tchemit@users.nuiton.org