2010-08-11 18 views
13

Duplicar posible:
Is there an equivalent of ‘which’ on windows?unix comando equivalente "which java" en windows?

No se ha podido encontrar en Google, pero preguntando si hay una manera de revelar la ubicación de Java por un comando equivalente de la solicitud de Windows.

Básicamente tengo información del cliente que él no establece el JAVA_HOME pero aún puede ejecutar programas Java. Sospecho que debe ser así porque la ruta de acceso a esa java se establece en la variable de entorno PATH del sistema, pero eso es demasiado largo para iterar de una manera rápida, también muy dolorosa (tiene que profundizar en las subcarpetas).

Gracias por cualquier sugerencia con anticipación!

+0

¿Demasiado tiempo para iterar? Cree un script/pequeño programa que lo itere por usted. Solo separe por ";" No hay necesidad de profundizar en las subcarpetas. – OscarRyz

+3

Nota: 'JAVA_HOME' debe apuntar a JDK. Ejecutar programas Java no requiere JDK, solo un JRE también es suficiente. La gran mayoría de los usuarios finales solo tienen un JRE. – BalusC

+0

@OscarRyz: eso es factible, solo tengo curiosidad de saber si hay una manera directa de indicar la ubicación de java ejecutando un comando simple desde cmd :) –

Respuesta

27

que puede probar:

c:\> for %i in (java.exe) do @echo. %~$PATH:i 
    C:\WINDOWS\system32\java.exe 

Esta es una característica del sistema de Windows for y se puede utilizar for /? para obtener los detalles:

 
In addition, substitution of FOR variable references has been enhanced. 
You can now use the following optional syntax: 
    %~I   - expands %I removing any surrounding quotes (") 
    %~fI  - expands %I to a fully qualified path name 
    %~dI  - expands %I to a drive letter only 
    %~pI  - expands %I to a path only 
    %~nI  - expands %I to a file name only 
    %~xI  - expands %I to a file extension only 
    %~sI  - expanded path contains short names only 
    %~aI  - expands %I to file attributes of file 
    %~tI  - expands %I to date/time of file 
    %~zI  - expands %I to size of file 
    %~$PATH:I - searches the directories listed in the PATH 
        environment variable and expands %I to the 
        fully qualified name of the first one found. 
        If the environment variable name is not 
        defined or the file is not found by the 
        search, then this modifier expands to the 
        empty string 

The modifiers can be combined to get compound results: 
    %~dpI  - expands %I to a drive letter and path only 
    %~nxI  - expands %I to a file name and extension only 
    %~fsI  - expands %I to a full path name with short names only 
    %~dp$PATH:I - searches the directories listed in the PATH 
        environment variable for %I and expands to the 
        drive letter and path of the first one found. 
    %~ftzaI  - expands %I to a DIR like output line 

In the above examples %I and PATH can be replaced by other valid 
values. The %~ syntax is terminated by a valid FOR variable name. 
Picking upper case variable names like %I makes it more readable and 
avoids confusion with the modifiers, which are not case sensitive. 
+0

@paxdiablo: solución fantástica, ¿puedo saber que esto es un script de PowerShell? ¿o no? –

+1

No, estándar 'cmd.exe'. Mucha gente parece pensar que no ha cambiado desde la versión de DOS con muerte cerebral pero en realidad ha llegado de una manera justa. En ninguna parte tan bueno como mi querido 'bash', por supuesto, pero viable :-) – paxdiablo

+0

Puede funcionar. ¡Feo definitivamente! No te encanta cómo implementan esto como un caso especial para el comando 'for' ... en lugar de como una característica general de% sustitución de variable. –

2

Esto es lo que normalmente utilizo. Si lo estuviese haciendo otra vez hoy, probablemente lo haría de manera un poco diferente, pero funciona lo suficientemente bien como para no tener ningún motivo para mirarlo durante años (de hecho, estoy bastante seguro de que la última vez hice nada a ella añadía "cmd" en la lista de extensiones cuando portado desde DOS para Win32 ...

// Which.c: 
#include <io.h> 
#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

char *extensions[] = { "com", "exe", "bat", "cmd", NULL }; 

int is_exe(char *ext) { 

    int i; 

    for (i = 0; extensions[i]; i++) 
     if (0 == stricmp(ext, extensions[i])) 
      return 1; 
    return 0; 
} 

int main(int argc, char **argv) { 

    char path[FILENAME_MAX]; 
    char buffer[FILENAME_MAX]; 
    char *path_var; 
    char *ext; 
    char *dir; 
    int i; 

    if (argc != 2) { 
     fprintf(stderr, "Usage: which <filename>\n"); 
     return 1; 
    } 

/* First try to find file name as-is. 
*/ 
    if (0 == access(argv[1], 0)) { 
     printf("\n%s", argv[1]); 
     return 0; 
    } 

/* Okay, it wasn't found. See if it had an extension, and if not, try 
* adding the usual ones... 
*/ 

    ext = strrchr(argv[1], '.'); 

    if (0 == ext++ || !is_exe(ext)) { 
     for (i = 0; extensions[i]; i++) { 

      sprintf(buffer, "%s.%s", argv[1], extensions[i]); 

      if (0 == access(buffer, 0)) { 
       printf("\n%s", buffer); 
       return 0; 
      } 
     } 

     if (NULL == (path_var=getenv("PATH"))) 
      return 1; 

     dir = strtok(path_var, ";"); 
     do { 
      for (i = 0; extensions[i]; i++) { 

       sprintf(buffer, "%s\\%s.%s", dir, argv[1], extensions[i]); 

       if (0 == access(buffer, 0)) { 
        printf("\n%s", buffer); 
        return 0; 
       } 
      } 
     } while (NULL != (dir = strtok(NULL, ";"))); 
    } 

    else { 
     if (NULL == (path_var=getenv("PATH"))) 
      return 1; 

     dir = strtok(path_var, ";"); 
     do { 
      sprintf(buffer, "%s\\%s", dir, argv[1]); 

      if (0 == access(buffer, 0)) { 
       printf("\n%s", buffer); 
       return 0; 
      } 
     } while (NULL != (dir = strtok(NULL, ";"))); 
    } 
    return 1; 
} 
1

las otras respuestas se ven bien. para completar, voy a añadir que también puede distribuir el JRE con su aplicación. No es tan elegante como las otras soluciones, pero funcionará y no tendrá que preocuparse por la versión de java que tenga el cliente.

3

¿Me falta algo aquí? ¿Qué tal probar el folio? lowing líneas de comando simples?

c:> dir/s java.exe

o

c:> dir/s javaw.exe

Se tomarán tiempo, pero que van a trabajar. Si desea hacerlo más rápido, comience en "c: \ Archivos de programa"

+1

Su enfoque tipo "encontrar" definitivamente está bien. La respuesta aceptada comprueba la variable del entorno del sistema% PATH% porque si bajo cualquier directorio "java -version" está bien, generalmente significa que la ubicación de java.exe se ha agregado a la ruta del sistema. Entonces creo que es mejor en términos de velocidad :) –

Cuestiones relacionadas