2009-08-18 56 views
21

Necesito hacer que los archivos y las carpetas estén ocultos tanto en Windows como en Linux. Sé que se agrega un '.' al frente de un archivo o carpeta lo ocultará en Linux. ¿Cómo puedo ocultar un archivo o una carpeta en Windows?Crear un archivo/carpeta oculta en Windows con Java

Respuesta

19

Para Java 6 y por debajo,

Usted tendrá que utilizar una llamada nativa, aquí es una manera de ventanas

Runtime.getRuntime().exec("attrib +H myHiddenFile.java"); 

Debe conocer un poco acerca de Win32 API o Java nativo.

+4

"nativo" significa que se está ejecutando el código específico de la plataforma. 'exec()' dispara un shell DOS/Windows para ejecutar un programa DOS/Windows. –

+0

¡Eres un salvavidas! –

+0

¿Qué sucede cuando este código se ejecuta en Linux? ¿O cómo lo evito? – Xerus

20

La funcionalidad que se desea es una característica de NIO.2 en la próxima Java 7.

He aquí un artículo que describe cómo va a ser utilizado para lo que necesita: Managing Metadata (File and File Store Attributes). Hay un ejemplo con DOS File Attributes:

Path file = ...; 
try { 
    DosFileAttributes attr = Attributes.readDosFileAttributes(file); 
    System.out.println("isReadOnly is " + attr.isReadOnly()); 
    System.out.println("isHidden is " + attr.isHidden()); 
    System.out.println("isArchive is " + attr.isArchive()); 
    System.out.println("isSystem is " + attr.isSystem()); 
} catch (IOException x) { 
    System.err.println("DOS file attributes not supported:" + x); 
} 

atributos ajuste se puede hacer usando DosFileAttributeView

Teniendo en cuenta estos hechos, no creo que hay una norma y elegante manera de lograr eso en Java 6 o Java 5.

3

esto es lo que yo uso:

void hide(File src) throws InterruptedException, IOException { 
    // win32 command line variant 
    Process p = Runtime.getRuntime().exec("attrib +h " + src.getPath()); 
    p.waitFor(); // p.waitFor() important, so that the file really appears as hidden immediately after function exit. 
} 
13

Java 7 puede ocultar un fichero del DOS de esta manera:

Path path = ...; 
Boolean hidden = path.getAttribute("dos:hidden", LinkOption.NOFOLLOW_LINKS); 
if (hidden != null && !hidden) { 
    path.setAttribute("dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS); 
} 

Los primeros Java-s no pueden.

El código anterior no generará una excepción en sistemas de archivos que no sean DOS. Si el nombre del archivo comienza con un punto, entonces también estará oculto en los sistemas de archivos UNIX.

+0

El método getAttribute (String, LinkOption) no está definido para el tipo java.nio.file.Path (JDK 7u13) – Antonio

+1

Antonio, debe haber sido así en la versión borrador de Java 7 que utilicé. Veo que una funcionalidad similar ahora está en java.nio.file.Files. –

+5

Puede usar 'Files.setAttribute' que aceptará una' Ruta' para establecer el atributo. –

0
String cmd1[] = {"attrib","+h",file/folder path}; 
Runtime.getRuntime().exec(cmd1); 

utilizar el código que se podría resolver un problema

2

en las ventanas, usando NIO de Java, archivos

Path path = Paths.get(..); //< input target path 
Files.write(path, data_byte, StandardOpenOption.CREATE_NEW); //< if file not exist, create 
Files.setAttribute(path, "dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS); //< set hidden attribute 
+2

Agregue una descripción de cómo el código que publicó responde la pregunta del usuario – Suever

1

Aquí es un totalmente compilables Java 7 ejemplo de código que oculta un archivo arbitrario en Windows .

import java.nio.file.Files; 
import java.nio.file.Path; 
import java.nio.file.Paths; 
import java.nio.file.attribute.DosFileAttributes; 


class A { 
    public static void main(String[] args) throws Exception 
    { 
     //locate the full path to the file e.g. c:\a\b\Log.txt 
     Path p = Paths.get("c:\\a\\b\\Log.txt"); 

     //link file to DosFileAttributes 
     DosFileAttributes dos = Files.readAttributes(p, DosFileAttributes.class); 

     //hide the Log file 
     Files.setAttribute(p, "dos:hidden", true); 

     System.out.println(dos.isHidden()); 

    } 
} 

Verificar que el archivo esté oculto. Haga clic derecho en el archivo en cuestión y verá después de la ejecución de la corte que el archivo en cuestión está realmente oculto.

enter image description here

Cuestiones relacionadas