Class FileUtil

java.lang.Object
org.nuiton.util.FileUtil

public class FileUtil extends Object
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...

Created: 22 novembre 2004

Author:
Benjamin Poussin - poussin@codelutin.com, Tony Chemit - chemit@codelutin.com
  • Field Details

    • ENCODING

      public static final String ENCODING
      Encoding utilisé (peut être redéfini)
  • Constructor Details

    • FileUtil

      public FileUtil()
  • Method Details

    • byteToFile

      public static File byteToFile(byte[] bytes) throws IOException
      Permet de convertir des bytes en fichier, le fichier sera automatiquement supprimé a la fin de la JVM.
      Parameters:
      bytes - the array of bytes to copy in dstination file
      Returns:
      le fichier temporaire contenant les bytes
      Throws:
      IOException - if any io pb
    • getReader

      public static BufferedReader getReader(File file) throws IOException
      Retourne un Reader utilisant l'encoding par defaut ENCODING.
      Parameters:
      file - the given reader
      Returns:
      the reader on the given file
      Throws:
      IOException - if any io pb
    • getReader

      public static BufferedReader getReader(File file, String encoding) throws IOException
      Retourne un reader utilisant l'encoding choisi et placé dans un BufferedReader
      Parameters:
      file - the given file
      encoding - (ISO-8859-1, UTF-8, ...)
      Returns:
      the buffered reader in the given encoding
      Throws:
      IOException - if any io pb
    • getWriter

      public static BufferedWriter getWriter(File file) throws IOException
      Retourne un Writer utilisant l'encoding par defaut ENCODING.
      Parameters:
      file - the given file
      Returns:
      the writer on the given file
      Throws:
      IOException - if any io pb
    • getWriter

      public static BufferedWriter getWriter(File file, String encoding) throws IOException
      Retourne un writer utilisant l'encoding choisi et placé dans un BufferedWriter
      Parameters:
      file - the given file
      encoding - (ISO-8859-1, UTF-8, ...)
      Returns:
      the buffered writer on the given file with given encoding
      Throws:
      IOException - if any io pb
    • createTempDirectory

      public static File createTempDirectory(String prefix, String suffix, File tmpdir) throws IOException
      Permet de creer un nouveu repertoire temporaire, l'effacement du répertoire est a la charge de l'appelant
      Parameters:
      prefix - le prefix du fichier
      suffix - le suffix du fichier
      tmpdir - le répertoire temporaire ou il faut creer le repertoire si null on utilise java.io.tmpdir
      Returns:
      le fichier pointant sur le nouveau repertoire
      Throws:
      IOException - if any io pb
    • createTempDirectory

      public static File createTempDirectory(String prefix, String suffix) throws IOException
      Permet de creer un nouveu repertoire temporaire, l'effacement du répertoire est a la charge de l'appelant
      Parameters:
      prefix - le prefix du repertoire a creer
      suffix - le suffix du repertoire a creer.
      Returns:
      the temprary created file
      Throws:
      IOException - if any io pb
    • getTempFile

      public static File getTempFile(String content) throws IOException
      Permet de donner une representation fichier pour une chaine de caractere. Le fichier sera automatiquement effacé à la fin de la JVM.
      Parameters:
      content - le contenu du fichier temporaire
      Returns:
      le fichier qui contient content
      Throws:
      IOException - if any io pb
    • getTempFile

      public static File getTempFile(String content, String fileSuffix) throws IOException
      Permet de donner une representation fichier pour une chaine de caractere. Le fichier sera automatiquement effacé à la fin de la JVM.
      Parameters:
      content - le contenu du fichier temporaire
      fileSuffix - l'extension du fichier créé
      Returns:
      le fichier qui contient content
      Throws:
      IOException - if any io pb
    • basename

      public static String basename(File file, String... suffixes)
      Equivalent de la methode basename unix. basename("/tmp/toto.xml", ".xml") → "toto"
      Parameters:
      file - le fichier dont on souhaite le nom sans le chemin
      suffixes - si present represente le suffixe a eliminer du fichier s'il est trouvé
      Returns:
      le nom du fichier sans le suffixe si trouvé.
    • basename

      public static String basename(String name, String... suffixes)
      Equivalent de la methode basename unix. basename("/tmp/toto.xml", ".xml") → "toto"
      Parameters:
      name - le nom du fichier dont on souhaite le nom sans le chemin
      suffixes - si present represente le suffixe a eliminer du fichier s'il est trouvé
      Returns:
      le nom du fichier sans le suffixe si trouvé.
      Since:
      1.4.2
    • extension

      public static String extension(File file, String... extchars)
      Permet de récupérer l'extension d'un fichier
      Parameters:
      file - le fichier dont on souhaite l'extension
      extchars - la liste des caracteres pouvant former l'extension dans l'ordre de preference. Si vide on utilise ".".
      Returns:
      l'extension ou la chaine vide si le fichier n'a pas d'extension l'extension ne contient pas le chaine de delimitation
    • extension

      public static String extension(String name, String... extchars)
      Permet de récupérer l'extension d'un nom de fichier
      Parameters:
      name - le nom du fichier dont on souhaite l'extension
      extchars - la liste des caracteres pouvant former l'extension dans l'ordre de preference. Si vide on utilise ".".
      Returns:
      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
    • changeExtension

      public static File changeExtension(File file, String newExtension, String... extchars) throws IOException
      Recupère le fichier dans le même répertoire que le fichier donné et dont on a changé l'extension.
      Parameters:
      file - le fichier d'origine
      newExtension - la nouvelle extension à utiliser
      extchars - la liste des extensions possibles
      Returns:
      le fichier dont on a changé l'extension
      Throws:
      IOException - si aucune extension trouvé dans le fichier d'origine
      Since:
      1.4.2
    • changeExtension

      public static String changeExtension(String name, String newExtension, String... extchars) throws IOException
      Change l'extension du fichier en entrée avec la nouvelle extension
      Parameters:
      name - le nom de fichier à transformer
      newExtension - la nouvelle extension à utiliser
      extchars - la liste des extensions possibles
      Returns:
      le nouveau nom de fichier
      Throws:
      IOException - si aucune extension trouvé dans le fichier d'origine
      Since:
      1.4.2
    • getRelativeFile

      public static File getRelativeFile(File inputDirectory, File outputDirectory, File file)
      Recupère le fichier mirroir du fichier file donnée qui est dans l'arborescence de inputDirectory dans le répertoire ouputDirectory.
      Parameters:
      inputDirectory - le répertoire de départ
      outputDirectory - le répertoire cible
      file - le fichier
      Returns:
      le fichier mirroir dans le répertoire cible
      Since:
      1.4.2
    • getSubDirectories

      public static List<File> getSubDirectories(File directory)
      Retourne tous les sous répertoires du répertoire passé en argument.
      Parameters:
      directory - un répertoire
      Returns:
      une liste d'objet File de répertoires et ceci recursivement à partir de directory, si directory n'est pas un répertoire la liste est vide.
    • getFiles

      public static List<File> getFiles(File directory)
      Retourne tous les fichiers du répertoire passé en argument.
      Parameters:
      directory - un répertoire
      Returns:
      une liste d'objet File des fichiers et ceci recursivement à partir de directory, si directory n'est pas un répertoire la liste est vide
    • find

      public static List<File> find(File directory, String pattern, boolean recursively)
      Retourne les fichiers d'un répertoire qui satisfont un certain pattern. La recherche est faite récursivement dans les sous répertoires
      Parameters:
      directory - le répertoire à partir duquel il faut faire la recherche
      pattern - le pattern que doit respecter le fichier pour être dans la liste résultante
      recursively - flag pour indiquer si on doit descendre dans les sous répertoires
      Returns:
      une liste d'objet File qui ont s'attisfait le pattern.
    • getFilteredElements

      public static List<File> getFilteredElements(File directory, FileFilter ff, boolean recursively)
      Retourne la liste de toutes les fichiers ou répertoire qui s'attisfont le filtre
      Parameters:
      directory - repertoire à partir duquel il faut faire la recherche
      ff - le filtre à appliquer pour savoir si le fichier parcouru doit être conservé dans les résultats, ou null pour tous les fichiers
      recursively - un flag pour indiquer si on doit descendre dans les répertoires
      Returns:
      une liste d'objet File, qui s'attisfont le filtre
    • walkAfter

      public static boolean walkAfter(File f, FileUtil.FileAction fileAction)
      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.
      Parameters:
      f - le fichier ou répertoire à partir duquel il faut commencer
      fileAction - l'action à effectuer sur chaque fichier
      Returns:
      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
    • walkBefore

      public static boolean walkBefore(File f, FileUtil.FileAction fileAction)
      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.
      Parameters:
      f - le fichier ou répertoire à partir duquel il faut commencer
      fileAction - l'action à effectuer sur chaque fichier
      Returns:
      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
    • copyRecursively

      public static void copyRecursively(File srcDir, File destDir, String... includePatterns) throws IOException
      Copie recursivement le repertoire source dans le repertoire destination

      copyRecursively("/truc/titi", "/var/tmp") donnera le repertoire "/var/tmp/titi"

      Parameters:
      srcDir - le répertoire source à copier
      destDir - le répertoire destination où copier
      includePatterns - les patterns que doivent resperter les fichiers/repertoires pour etre copié. Si vide alors tout est copié
      Throws:
      IOException - if any io pb
    • copyAndRenameRecursively

      public static void copyAndRenameRecursively(File srcDir, File destDir, String renameFrom, String renameTo, String... includePatterns) throws IOException
      Copie recursivement le repertoire source dans le repertoire destination

      copyRecursively("/truc/titi", "/var/tmp", "bidulle") donnera le repertoire "/var/tmp/bidulle", 'bidulle' remplacant 'titi'

      Parameters:
      srcDir - le répertoire source à copier
      destDir - le répertoire destination où copier
      renameFrom - pattern to permit rename file before uncompress it
      renameTo - new name for file if renameFrom is applicable to it you can use $1, $2, ... if you have '(' ')' in renameFrom
      includePatterns - les patterns que doivent resperter les fichiers/repertoires pour etre copié. Si vide alors tout est copié
      Throws:
      IOException - if any io pb
    • copyAndRenameRecursively

      public static void copyAndRenameRecursively(File srcDir, File destDir, boolean includeSrcDir, String renameFrom, String renameTo, boolean exclude, String... includePatterns) throws IOException
      Copie recursivement le repertoire source dans le repertoire destination

      copyRecursively("/truc/titi", "/var/tmp", "bidulle") donnera le repertoire "/var/tmp/bidulle", 'bidulle' remplacant 'titi'

      Parameters:
      srcDir - le répertoire source à copier
      destDir - le répertoire destination où copier
      includeSrcDir - si vrai alors le repertoire source est copie dans le repertoire destination et non pas seulement les fichiers qu'il contient
      renameFrom - pattern to permit rename file before uncompress it
      renameTo - new name for file if renameFrom is applicable to it you can use $1, $2, ... if you have '(' ')' in renameFrom
      exclude - inverse include pattern interpretation
      includePatterns - les patterns que doivent resperter les fichiers/repertoires pour etre copié. Si vide alors tout est copié
      Throws:
      IOException - if any io pb
    • readBytesFrom

      public static ByteArrayOutputStream readBytesFrom(InputStream inputStream, int defaultBufferSize) throws IOException
      Get a ByteArrayOutputStream containing all data that could be read from the given InputStream
      Parameters:
      inputStream - the stream to read
      defaultBufferSize - the buffer size
      Returns:
      the input stream read for input
      Throws:
      IOException - if any pb while reading or writing
    • grep

      protected static List<CharSequence> grep(String regex, CharBuffer cb)
      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

      Parameters:
      regex - regex to search into file
      cb - nio buffer
      Returns:
      matching lines (or {code null} if no matching lines)
      Since:
      1.1.2
    • grep

      public static List<CharSequence> grep(String searchRegex, File f, String encoding) throws IOException
      Java implementation for the unix grep command.

      Code taken from :

      http://java.sun.com/javase/6/docs/technotes/guides/io/example/Grep.java

      May fail on windows with error : The requested operation cannot be performed on a file with a user-mapped section open

      Parameters:
      searchRegex - regex to search into file
      f - file to search into
      encoding - encoding to use
      Returns:
      matching lines (or {code null} if no matching lines)
      Throws:
      IOException - FIXME
      Since:
      1.1.2
    • grep

      public static Map<File, List<CharSequence>> grep(String searchRegex, File rootDirectory, String fileRegex, String encoding) throws IOException
      Java implementation for the unix grep command.

      May fail on windows with error : The requested operation cannot be performed on a file with a user-mapped section open

      Parameters:
      searchRegex - regex to search into file
      rootDirectory - directory to seacrh into
      fileRegex - regex for file to find in rootDirectory
      encoding - encoding to use
      Returns:
      all matching lines for each files
      Throws:
      IOException - FIXME
      Since:
      1.1.2
    • grep

      public static Map<File, List<CharSequence>> grep(String searchRegex, String fileRegex, String encoding) throws IOException
      Search for files matching regex in current directory.

      May fail on windows with error : The requested operation cannot be performed on a file with a user-mapped section open

      Parameters:
      searchRegex - regex to search into file
      fileRegex - regex for file to find in current dir
      encoding - encoding to use
      Returns:
      all matching lines for each files
      Throws:
      IOException - FIXME
      Since:
      1.1.2
    • sed

      public static void sed(String searchRegex, String replace, File file, String encoding) throws IOException
      Sed implementation for a single file.

      Oginal source code from http://kickjava.com/src/org/apache/lenya/util/SED.java.htm.

      May fail on windows with error : The requested operation cannot be performed on a file with a user-mapped section open

      Parameters:
      searchRegex - Prefix which shall be replaced
      replace - Prefix which is going to replace the original
      file - File which sed shall be applied
      encoding - charset encoding
      Throws:
      IOException - FIXME
      Since:
      1.1.2
    • sed

      public static void sed(String searchRegex, String replace, File rootDirectory, String fileRegex, String encoding) throws IOException
      Java implementation for the unix sed command.

      May fail on windows with error : The requested operation cannot be performed on a file with a user-mapped section open

      Parameters:
      searchRegex - regex to search into file
      replace - string to replace matching patterns
      rootDirectory - directory to search into
      fileRegex - regex for file to find in rootDirectory
      encoding - encoding to use
      Throws:
      IOException - FIXME
      Since:
      1.1.2
    • sed

      public static void sed(String searchRegex, String replace, String fileRegex, String encoding) throws IOException
      Java implementation for the unix sed command.

      May fail on windows with error : The requested operation cannot be performed on a file with a user-mapped section open

      Parameters:
      searchRegex - regex to search into file
      replace - string to replace matching patterns
      fileRegex - regex for file to find in current dir
      encoding - encoding to use
      Throws:
      IOException - FIXME
      Since:
      1.1.2
    • createDirectoryIfNecessary

      public static boolean createDirectoryIfNecessary(File dir)
      Create the directory (and his parents) if necessary.
      Parameters:
      dir - the directory to create if not exisiting
      Returns:
      true if directory was created, false if was no need to create it
      Since:
      1.3.2
    • getFileFromPaths

      public static File getFileFromPaths(File rootDirectory, String... paths)
      Obtain a file from the given rootDirectory, applying given paths.

      For example with paths = a, b and c, then result is :

      root/a/b/c
      
      Parameters:
      rootDirectory - the root directory
      paths - paths to apply
      Returns:
      the final file
      Since:
      2.2
    • getFileFromFQN

      public static File getFileFromFQN(File rootDirectory, String fqn)
      Obtain a file fro the given rootDirectory, applying the fqn.

      For example with fqn = a.b.c, the result is :

      root/a/b/c
      
      Parameters:
      rootDirectory - the root directory
      fqn - fqn of searched file
      Returns:
      the final file
      Since:
      2.2
    • getTestSpecificDirectory

      public static File getTestSpecificDirectory(Class<?> testClassName, String methodName, String classifier, long timestamp)
      Obtain a directory and creates it if required to place some test data.

      The directory will be :

          java.io.tmpdir/testclassName.fqn/methodName[/classifier]/timestamp
      
      Parameters:
      testClassName - test class name
      methodName - method name
      classifier - optional classifier
      timestamp - timestamp
      Returns:
      the computed and created if required directory.
      Since:
      2.6.10
    • isGzipFile

      public static boolean isGzipFile(File file) throws IOException
      Tests if a file is GZipped.
      Parameters:
      file - file to test
      Returns:
      true if file is gzipped, false otherwise
      Throws:
      IOException - if any io errors while reading file
      Since:
      3.0