public static File getMavenHome ( ) throws Exception { final String command ; switch ( OS . current ( ) ) { case LINUX : case MAC : command = "mvn" ; break ; case WINDOWS : command = "mvn.bat" ; break ; default : throw new IllegalStateException ( "invalid o/s" ) ; } String pathVar = System . getenv ( "PATH" ) ; String [ ] pathArray = pathVar . split ( File . pathSeparator ) ; for ( String path : pathArray ) { File file = new File ( path , command ) ; if ( file . exists ( ) && file . isFile ( ) && file . canExecute ( ) ) { /** unwrap symbolic links */ File exec = file . getCanonicalFile ( ) ; /** assume ${maven.home}/bin/exec convention */ File home = exec . getParentFile ( ) . getParentFile ( ) ; return home ; } } throw new IllegalStateException ( "Maven home not found." ) ; }
Discover maven home from executable on PATH using conventions .