Vous devez être membre et vous identifier pour publier un article.
Les visiteurs peuvent toutefois commenter chaque article par une réponse.

Java : répertoire de l’application

Astuces de l’Infobrol (Java)Article publié le 13/02/2009 11:01:41


Si dans une application Java nous désirons connaître le répertoire depuis lequel une classe est exécutée, la majorité des sites et forums dans lesquels la question est posée répondent qu’il faut utiliser la propriété système "user.dir".

Ce n’est pas totalement faux, mais cette propriété retourne en réalité le répertoire depuis lequel la commande est lancée.

Exemples




steph@astate:~$cd /media/DATA/steph/test
steph@astate:/media/DATA/steph/test$java -jar myTest.jar
path = /media/DATA/steph/test
jar found : ok
steph@astate:/media/DATA/steph/test$




Dans ce cas, nous positionnons le répertoire actif sur "/media/DATA/steph/test" qui est le répertoire qui contient le jar, puis nous exécutons le jar (qui effectue simplement une sortie de System.getProperty("user.dir"), puis vérifie si le jar se trouve dans le répertoire).
Le résultat affiché correspond bien au répertoire qui contient le jar.



steph@astate:~$java -jar /media/DATA/steph/test/myTest.jar
path = /home/steph
jar found : no
steph@astate:~$




Dans ce cas, nous invoquons la commande sans changer de répertoire actif, et le test échoue, car la propriété "user.dir" correspond au répertoire dans lequel nous nous trouvons au moment de lancer la commande.


Une solution...


Afin d’éviter ce genre de problème, j’utilise une classe statique dans laquelle j’ai placé différents codes nécessaires à la manipulation des fichiers :

  1. /**
  2. * {@link java.lang.System#getProperty(String)
  3. * System.getProperty("user.dir")} does not return class directory each
  4. * time. If we start a java application from a command prompt by giving the
  5. * path (not using ‹code›cd‹/code› command to set the active directory),
  6. * ‹code›user.dir‹/code› contains the active directory and not the
  7. * application directory.
  8. *
  9. * @param startingClass
  10. * class witch we need to know directory
  11. * @param cached
  12. * ‹ul›
  13. * ‹li›‹code›true‹/code› to avoid doing the parsing each time.
  14. * The result is stored as cache after the first call.‹/li›
  15. * ‹li›‹code›false‹/code› to ignore cached result (this does not
  16. * affect the cached result).
  17. *
  18. * @return path of the class arg
  19. *
  20. * @since 0.1.12-SNAPSHOT (Feb 12 2009)
  21. */
  22. public static String getApplicationPath(Class‹?› startingClass,
  23. boolean cached) {
  24.  
  25. if (!cached || applicationPath == null) {
  26.  
  27. String classDirectory = "/"
  28. + startingClass.getName().replace(’.’, ’/’) + ".class";
  29. // classDirectory = /be/gaudry/model/file/FileHelper.class
  30. System.out.println("FileHelper.getApplicationPath() 1 "+classDirectory);
  31.  
  32. URL url = FileHelper.class.getResource(classDirectory);
  33.  
  34. try {
  35.  
  36. classDirectory = URLDecoder.decode(url.toString(), "UTF-8");
  37. System.out.println("FileHelper.getApplicationPath() 2 "+classDirectory);
  38.  
  39. // This class is run from a jar file
  40. if (classDirectory.startsWith("jar:file:")) {
  41. // classDirectory =
  42. // jar:file:/media/DATA/steph/dev/java/projets/dist/EducaBrol-Full-jar-with-dependencies.jar!/be/gaudry/model/file/FileHelper.class
  43. System.out.println("FileHelper.getApplicationPath() 4 "+classDirectory);
  44.  
  45. // remove "jar:file:" string and classpath string from URL
  46. int index = classDirectory.indexOf("!");
  47. classDirectory = classDirectory.substring(9, index);
  48. // classDirectory =
  49. // /media/DATA/steph/dev/java/projets/dist/EducaBrol-Full-jar-with-dependencies.jar
  50. System.out.println("FileHelper.getApplicationPath() 5 "+classDirectory);
  51.  
  52. // remove jar name from URL
  53. index = classDirectory.lastIndexOf("/");
  54. classDirectory = classDirectory.substring(0, index);
  55. // classDirectory = /media/DATA/steph/dev/java/projets/dist
  56. System.out.println("FileHelper.getApplicationPath() 6 "+classDirectory);
  57.  
  58. } else {
  59. // This class is not in a jar file
  60.  
  61. // classDirectory =
  62. // file:/media/DATA/steph/dev/java/projets/broldev/core/broldev.core.model/target/classes/be/gaudry/model/file/FileHelper.class
  63. System.out.println("FileHelper.getApplicationPath() 7 "+classDirectory);
  64.  
  65. // remove file name and extension from URL
  66. int index = classDirectory.lastIndexOf("/");
  67. classDirectory = classDirectory.substring(0, index);
  68. // classDirectory =
  69. // file:/media/DATA/steph/dev/java/projets/broldev/core/broldev.core.model/target/classes/be/gaudry/model/file
  70. System.out.println("FileHelper.getApplicationPath() 8 "+classDirectory);
  71.  
  72. // remove file: prefix from URL
  73. classDirectory = classDirectory.substring(5, classDirectory
  74. .length());
  75. // classDirectory =
  76. // /media/DATA/steph/dev/java/projets/broldev/core/broldev.core.model/target/classes/be/gaudry/model/file
  77. System.out.println("FileHelper.getApplicationPath() 9 "+classDirectory);
  78.  
  79. Package pack = startingClass.getPackage();
  80. if (null != pack) {
  81. String packPath = pack.toString().replace(’.’, ’/’);
  82. // packPath = package be/gaudry/model/file
  83.  
  84. // remove package from URL
  85. if (classDirectory.endsWith(packPath.substring(8))) {
  86. classDirectory = classDirectory.substring(0,
  87. (classDirectory.length() - packPath
  88. .length()));
  89. // classDirectory =
  90. // /media/DATA/steph/dev/java/projets/broldev/core/broldev.core.model/target/
  91. System.out.println("FileHelper.getApplicationPath() 10 "+classDirectory);
  92. }
  93.  
  94. // remove maven structure from URL
  95. String maven = "target/";
  96. if (classDirectory.endsWith(maven)) {
  97. classDirectory = classDirectory.substring(0,
  98. (classDirectory.length() - maven.length()));
  99. // classDirectory =
  100. // /media/DATA/steph/dev/java/projets/broldev/core/broldev.core.model/
  101. System.out.println("FileHelper.getApplicationPath() 11 "+classDirectory);
  102. }
  103. }
  104. }
  105.  
  106. // Windows path may not start with "/" before drive letter
  107. if (File.separator.equals("\\\\")) {
  108. classDirectory = classDirectory.substring(1);
  109. System.out.println("FileHelper.getApplicationPath() 3 "+classDirectory);
  110. }
  111.  
  112. } catch (Exception e) {
  113. e.printStackTrace();
  114. }
  115.  
  116. if (!cached) {
  117. return classDirectory;
  118. }
  119. applicationPath = classDirectory;
  120. }
  121. return applicationPath;
  122. }


Avatar :: Steph Un article de Steph

Source : indéterminée


Sélection, tri et recherche d'articles
FILTRER :
TRIER :1er critère : 2e critère :
CHERCHER : Dans les titres Dans le contenu


[Afficher les liens en fonction des critères du formulaire ci-dessus]

Document créé le 13/09/2004, dernière modification le 26/10/2018
Source du document imprimé : https://www.gaudry.be/ast-rf-448.html

L'infobrol est un site personnel dont le contenu n'engage que moi. Le texte est mis à disposition sous licence CreativeCommons(BY-NC-SA). Plus d'info sur les conditions d'utilisation et sur l'auteur.