Foros del Web » Programación para mayores de 30 ;) » Java »

Recorrer directorio Con Subcarpetas

Estas en el tema de Recorrer directorio Con Subcarpetas en el foro de Java en Foros del Web. Hola, quiero recorrer un directorio en el cual tengo muchas subcarpetas y en cada subcarpeta tengo 5 archivos .txt que son los que me gustarian ...
  #1 (permalink)  
Antiguo 14/05/2013, 12:11
 
Fecha de Ingreso: abril-2013
Mensajes: 53
Antigüedad: 11 años
Puntos: 0
Recorrer directorio Con Subcarpetas

Hola, quiero recorrer un directorio en el cual tengo muchas subcarpetas y en cada subcarpeta tengo 5 archivos .txt que son los que me gustarian guardar cada 1 en un string .

lo he conseguido hacer el c pero no se en java.

Código HTML:
            string bold;
            string text;
            string textIMG;
            string title;
            string underline;
            string id;

             for (int i = 0; i < carpetas.Length; i++)
             {
                 string[] files = System.IO.Directory.GetFiles(directoryFiles + "/" +i + "/", "*.txt");// aquí esta la cuestión.

                 Document doc = new Document();
                
                 bold = leerFichero(files[0]);//el files[0] es al leerlo como sta ordenado siembre es la posicion 0 y asi con todos
                 text = leerFichero(files[1]);
                 textIMG = leerFichero(files[2]);
                 title = leerFichero(files[3]);
                 underline = leerFichero(files[4]);

                 id = i.ToString();
como seria en java?

un saludo y muchas gracias
  #2 (permalink)  
Antiguo 14/05/2013, 14:22
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Recorrer directorio Con Subcarpetas

Es bastante fácil. Recorre todos los archivos en forma de árbol con las carpetas como padres y los archivos como hojas y listo.

Código Java:
Ver original
  1. import java.io.File;
  2.  
  3. public class Utils {
  4.     public static void main(String[] args) {
  5.         walkin(new File("/home/user")); //Replace this with a suitable directory
  6.     }
  7.  
  8.     public static void walkin(File dir) {
  9.  
  10.         File listFile[] = dir.listFiles();
  11.         if (listFile != null) {
  12.             for (int i = 0; i < listFile.length; i++) {
  13.                 if (listFile[i].isDirectory()) {
  14.                     walkin(listFile[i]);
  15.                 } else {
  16.                     System.out.println(listFile[i].getPath());
  17.                 }
  18.             }
  19.         }
  20.     }
  21. }
Fuente: http://rosettacode.org/wiki/Walk_a_d...cursively#Java
  #3 (permalink)  
Antiguo 14/05/2013, 17:11
 
Fecha de Ingreso: abril-2013
Mensajes: 53
Antigüedad: 11 años
Puntos: 0
Respuesta: Recorrer directorio Con Subcarpetas

Hola, pero ahora que he recorrido todas las carpetas y los 5 archivos de dentro de cada 1 como le digo que bold corresponde a la posición 0 de dentro de la carpeta y asi con las otras 4?
tittle corresponde a la 3.
con esto:
bold = leerFichero(files[0]); le digo el bold = a leer el fichero 0, pero no se en java.
  #4 (permalink)  
Antiguo 14/05/2013, 18:14
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Recorrer directorio Con Subcarpetas

Después de leer tu pregunta varias veces y no entenderle preferí leer el código que pusiste y ahora tiene mas sentido.

Solamente necesitas una clase extra, que en este caso le llamamos Filter y

Código Java:
Ver original
  1. import java.io.File;
  2. import java.io.FilenameFilter;
  3.  
  4. public class Filter {
  5.  
  6.     public File[] finder(String dirName){
  7.         File dir = new File(dirName);
  8.  
  9.         return dir.listFiles(new FilenameFilter() {
  10.                  public boolean accept(File dir, String filename)
  11.                       { return filename.endsWith(".txt"); }
  12.         } );
  13.  
  14.     }
  15.  
  16. }

Sustiturla:
Código Java:
Ver original
  1. String bold;
  2. String text;
  3. String textIMG;
  4. String title;
  5. String underline;
  6. String id;
  7.  
  8. for (int i = 0; i < carpetas.Length; i++)
  9. {
  10.     File[] files = Filter().finder(directoryFiles + "/" + i + "/");
  11.  
  12.     Document doc = new Document();
  13.    
  14.     bold = leerFichero(files[0].getPath());
  15.     text = leerFichero(files[1].getPath());
  16.     textIMG = leerFichero(files[2].getPath());
  17.     title = leerFichero(files[3].getPath());
  18.     underline = leerFichero(files[4].getPath());
  19.  
  20.     id = i.ToString();
  21. }

Última edición por razpeitia; 16/05/2013 a las 14:42
  #5 (permalink)  
Antiguo 14/05/2013, 18:57
 
Fecha de Ingreso: abril-2013
Mensajes: 53
Antigüedad: 11 años
Puntos: 0
Respuesta: Recorrer directorio Con Subcarpetas

No consigo nada. intentare explicar mi project, es un buscador en lucene ahora mismo estoy creando un directorio y una carpeta donde indexar los documentos. este es mi codigo en java:
Código HTML:
import org.apache.lucene.index.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.es.SpanishAnalyzer;
import org.apache.lucene.document.*;
import java.io.*;
import java.util.ArrayList;

public class CreaIndice {
	public static void main(String[] args) throws Exception {

		File directorioGuardarIndice = new File("c:/Temp/indice");//crear carpeta indice
		File Documentos = new File("c:/Temp/documentos");//crear carpeta con los documentos a indexar

		Directory RecorreDirectorio = FSDirectory.open(directorioGuardarIndice);

		
		Analyzer analizador = new SpanishAnalyzer(Version.LUCENE_31);//analizador

		IndexWriterConfig configuracionIndice = new IndexWriterConfig(
				Version.LUCENE_31, analizador);

		IndexWriter Indice = new IndexWriter(RecorreDirectorio, configuracionIndice);

		String bold;
        String text;
        String textIMG;
        String title;
        String underline;
        
        String id;
		
		File[] archivos = Documentos.listFiles();//asigna a archivos los documentos de la carpeta
		for (int i = 0; i < archivos.length; i++) {
			
			File f = archivos[i];//asigna a f los archivos recorri
			
			if (!f.isDirectory() && !f.isHidden() && f.exists() && f.canRead()
					&& (f.getName().endsWith(".txt"))) {
				System.out.println("Indexing " + f.getCanonicalPath());
				Document doc = new Document();
				
				
				
				
				//bold = leerFichero(File[0]);
                /*text = leerFichero(File[1]);
                textIMG = leerFichero(File[2]);
                title = leerFichero(File[3]);
                underline = leerFichero(File[4]);
                */

				//prueba: asi si indexa bien todos los terminos pero metiendole tu un valor a bolde
				String bolde = "This is the text to be indexed.";
			    doc.add(new Field("bolde", bolde, Field.Store.YES,
			    Field.Index.ANALYZED));
			    
			    String title2 = "prueba con el titulo acné  sábado dolores";
			    doc.add(new Field("title2", title2, Field.Store.YES,
			    Field.Index.ANALYZED));
				
				 
				/* asi no indexa bien el problema es la lectura creo
				// Campo nombre archivo
				//Field camponombre = new Field("rutaArchivo", new InputStreamReader(new FileInputStream(f), "UTF-8"));
				//doc.add(camponombre);
				Field camponombres = new Field("rutaArchivo", f.getName(),Field.Store.YES, Field.Index.ANALYZED);
				doc.add(camponombres);
				//id
				
				Field campoid = new Field("id", f.getName(),Field.Store.YES, Field.Index.ANALYZED);
				doc.add(campoid);
				// Campo contenido del archivo
				Field campocontenido = new Field("contenido", f.getName(),Field.Store.YES, Field.Index.ANALYZED);
				doc.add(campocontenido);
				// Campo bold
				Field campobold = new Field("bold", f.getName(),Field.Store.YES, Field.Index.ANALYZED);
				doc.add(campobold);
				// Campo textimg
				Field campotextimg = new Field("textimg", f.getName(),Field.Store.YES, Field.Index.ANALYZED);
				doc.add(campotextimg);
				// Campo title
				Field campotitle = new Field("title", f.getName(),Field.Store.YES, Field.Index.ANALYZED);
				doc.add(campotitle);
				// Campo underlineWords
				Field campounderlineWords = new Field("underlineWords", f.getName(),Field.Store.YES, Field.Index.ANALYZED);
				doc.add(campounderlineWords);
								
				
				
				*/
				
				
				
				Indice.addDocument(doc);
			}
		}
		Indice.optimize();
		Indice.close();
		System.out.println("el numero de documentos indexados es "
				+ Indice.numDocs());
	}
}
pero no indexa bien, si le paso el string escrito si, pero yo quiero lo que he comentado antes k sepa que el campo bold es el primer termino a leer .para luego pasárle ese valor ya leído a Field para indexarlo.

Este es mi código en c que no se adaptarlo
Código HTML:
 private void BIndexar_Click(object sender, EventArgs e)
        {
            
            String directoryIndex = @"C:\Users\Laura\Documents\Proyectointel\LuceIndex";

            ISet<string> stopWords=new HashSet<string>(SPANISH_STOP_WORDS);

            Analyzer analyzer = new SnowballAnalyzer(Lucene.Net.Util.Version.LUCENE_30, "Spanish", stopWords);

            IndexWriter writer = new IndexWriter(FSDirectory.Open(directoryIndex), analyzer, true, IndexWriter.MaxFieldLength.LIMITED);

            String directoryFiles = @"C:\Users\Laura\Documents\Proyectointel\textoplano";

            stopWatch = new Stopwatch();
            stopWatch.Start();

            string[] carpetas = System.IO.Directory.GetDirectories(directoryFiles);

            string bold;
            string text;
            string textIMG;
            string title;
            string underline;
            string id;

             for (int i = 0; i < carpetas.Length; i++)
             {
                 string[] files = System.IO.Directory.GetFiles(directoryFiles + "/" +i + "/", "*.txt");

                 Document doc = new Document();
                
                 bold = leerFichero(files[0]);
                 text = leerFichero(files[1]);
                 textIMG = leerFichero(files[2]);
                 title = leerFichero(files[3]);
                 underline = leerFichero(files[4]);

                 id = i.ToString();

                 doc.Add(new Field("bold", bold, Field.Store.YES, Field.Index.ANALYZED));
                 doc.Add(new Field("text", text, Field.Store.YES, Field.Index.ANALYZED));
                 doc.Add(new Field("textIMG", textIMG, Field.Store.YES, Field.Index.ANALYZED));
                 doc.Add(new Field("title", title, Field.Store.YES, Field.Index.ANALYZED));
                 doc.Add(new Field("underline", underline, Field.Store.YES, Field.Index.ANALYZED));
                 doc.Add(new Field("id", id, Field.Store.YES, Field.Index.NOT_ANALYZED));

                 writer.AddDocument(doc);
                 LBLucene.Items.Add("Indexado archivo: " + i);
             }

             writer.Optimize();
             writer.Dispose();
             stopWatch.Stop();
             LBLucene.Items.Add("Indexado en: " + getTime());
             LBLucene.TopIndex = LBLucene.Items.Count - 1;
        }
  #6 (permalink)  
Antiguo 16/05/2013, 13:35
 
Fecha de Ingreso: abril-2013
Mensajes: 53
Antigüedad: 11 años
Puntos: 0
Respuesta: Recorrer directorio Con Subcarpetas

Hola, compañero me he creado la clase filter, pero me da fallo en la otra clase en esta linea

Código HTML:
File[] files = Filter().finder(directoryFiles + "/" + i + "/");
me dice k filter() no esta declarado.
  #7 (permalink)  
Antiguo 16/05/2013, 14:44
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Recorrer directorio Con Subcarpetas

Tienes que poner File[] files = new Filter().finder(directoryFiles + "/" + i + "/");

Y ademas recuerda que tienes que crear la clase Filter la implementación esta allá arriba.
  #8 (permalink)  
Antiguo 16/05/2013, 14:55
 
Fecha de Ingreso: abril-2013
Mensajes: 53
Antigüedad: 11 años
Puntos: 0
Respuesta: Recorrer directorio Con Subcarpetas

vale muchas gracias,

me da fallo otro en estas lineas
Código HTML:
    bold = leerFichero(files[0].getPath());
    text = leerFichero(files[1].getPath());
    textIMG = leerFichero(files[2].getPath());
    title = leerFichero(files[3].getPath());
    underline = leerFichero(files[4].getPath());
    id = i.ToString();
esto es xk me tengo que declarar una class leerFichero no?

Perdona mi ignorancia pero soy nuevo en java y quiero aprender. gracias por todo
  #9 (permalink)  
Antiguo 16/05/2013, 16:33
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Recorrer directorio Con Subcarpetas

ehm, eso mas bien es un método que regresa un string y la verdad esa parte la copie y pegue de tu código por que supuse que así lo tenias.
  #10 (permalink)  
Antiguo 16/05/2013, 17:30
 
Fecha de Ingreso: abril-2013
Mensajes: 53
Antigüedad: 11 años
Puntos: 0
Respuesta: Recorrer directorio Con Subcarpetas

asi es como lo tenia en c:

Código HTML:
bold = leerFichero(files[0]);
                 text = leerFichero(files[1]);
                 textIMG = leerFichero(files[2]);
                 title = leerFichero(files[3]);
                 underline = leerFichero(files[4]);
tenia pensado hacer un leerFichero y como bold es la primera alfabéticamente pues por eso el files[0] y así con todos. xk luego necesito lo que contiene bold para utilizarlo, para indexar. por eso necesitaba esta linea

Código HTML:
File[] files = new Filter().finder(directoryFiles + "/" + i + "/");
que es donde leo el fichero para el Files.

¿Ese no es el camino que tengo que buscar?
  #11 (permalink)  
Antiguo 16/05/2013, 20:39
 
Fecha de Ingreso: marzo-2012
Ubicación: Argentina
Mensajes: 111
Antigüedad: 12 años, 1 mes
Puntos: 12
Respuesta: Recorrer directorio Con Subcarpetas

Mira si usas java 7 es bastante simple aca hay un tuto

http://codecriticon.com/ficheros-java-7-i/

Saludos.

Etiquetas: directorio, string, subcarpetas
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:55.