Comprobar que se va a utilizar X archivo y no el archivo Z [Java]

Iniciado por r00t_access, Junio 17, 2015, 01:54:28 PM

Tema anterior - Siguiente tema

0 Miembros y 1 Visitante están viendo este tema.

Junio 17, 2015, 01:54:28 PM Ultima modificación: Junio 18, 2015, 06:50:01 AM por blackdrake
Buenas!

Sigo con Java... empiezo a cogerle manía :S Aquí planteo mi duda:

Teniendo un .txt, me gustaría saber como escribir un code que saque las palabras con una terminación dada por el usuario así como el numero de veces que aparece dicha palabras. Este sería el esquema a seguir:

1. Al ejecutarlo se le pide al usuario el nombre del archivo que tiene que escribirse con la extensión(ejemplo.txt)

2. Si el nombre introducido no se encuentra en la carpeta src, aparecerá el pensaje de archivo no encontrado vuelva a intentarlo, es decir, que vuelve al primero apartado de introducción de texto.

3. Si el nombre del archivo es el mismo que el nombre del txt de la carpeta src se le preguntara al usuario que terminación tienen que tener las palabras a buscar.

4. Tras escribir la terminación aparecerá en pantalla una lista con las palabras que terminan por la terminación escrita anteriormente. En la lista han de aparecer también el numero de veces que ha aparecido dicha palabra.

5. Si cuando el se ejecuta el programa el usuario escribe "end" el programa se dentendrá.

Y ahora un poco mas resumido:

User -> nombre del archivo: (input)
           if nombre del archivo introducido.exist():
                  user -> que terminación tienen que tener las palabras que vamos a buscar: (input)
                          System.out.print(lista de palabras con esa terminación + numero de veces que aparecen)

          si el usuario escribe "end" -> Sysyem.exit(1)


Por ahora lo que llevo es esto:

Código: java
import java.io.Archivo;
import java.io.FileNotFoundException;
import java.util.regex.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MorphSearchDemo extends ChatReader{

//variables
String suffix;
List<String> tokenS = new ArrayList<String>(); //Contendrá las palabras que terminen con la terminacion indicada

String Archivo;
String Terminacion;

public MorphSearchDemo(String Archivoname, String suffix) {
super(Archivoname);
this.suffix=suffix;
}

public String searchS() throws FileNotFoundException{

        Scanner scan = new Scanner(System.in);
        System.out.print("introduce el nombre del archivo: "+ "\n");
        this.Archivo = scan.next();
        if(!this.Archivo.contains(".")){ // para asegurarme de que el user pone la extension! Pero quiero limitar las opciones del user y que
        System.out.print("el archivo existe, vueleve a intentarlo"); // solo pueda escribir el nombre de los archivos que hay en src
        }
        //System.out.println( "input = " + input );
        /*if (!(input != Archivo)){
        for (String rs : getMessages()){
   
    String[] splitString = rs.split(" ");
   
    for (int i=0; i<splitString.length; i++){
   
    Pattern patternS = Pattern.compile(suffix);
    Matcher matcherS = patternS.matcher(splitString[i]);
   
    if (matcherS.find()){ //if we found a token matching endS
    splitString[i]=splitString[i].replaceAll("[^A-Za-z ]", ""); //quito todos los caracteres especiales y numeros
    tokenS.add(splitString[i]);
    }
    }
    }
        System.out.println(tokenS.toString());
        }*/
        System.out.print("Terminacion : ");
        this.Terminacion = scan.next();
        if (this.Terminacion.contains("end") || this.Archivo.contains("end")){     // si el usuario escribe end tiene que terminar de correr
        System.out.print("el proceso ha terminado");
        System.exit(0);
            }
       
       
       
        //Archivo Archivo = new Archivo(dat.nextLine());
        //dat = new Scanner(Archivo);
       

//look for the pattern in each token of each line

//System.out.println(tokenS.toString());
return " ";
}

}


Esto es lo poco que llevo y ya me he atascado. El reader lo tengo en otro archivo que no creo que rea muy importante ya que me lo he probado y me lee el texto y he probado lo de que encuentre las palabras terminadas en X y me ha funcionado bien.

Otro problema esta en que al correr el programa si cuando pide el nombre del archivo escribo end pasa directamente a preguntarme la terminación a buscar y si ahí escribo end ya si me dice lo de proceso finalizado :S

Alguien podría darme algún empujón?
Ya que escribo esto, alguien me puede decir que diferencia hay entre escribir un numero u otro en el System.exit(int);


Código: java
package org.underc0de.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CharsFinder {
public boolean checkExt(String fileName) {
if (fileName.endsWith(".txt")) {
return true;
}
return false;
}

public boolean exists(String fileName) {
try {
InputStream is = CharsFinder.class.getClassLoader()
.getResourceAsStream(fileName);
is.available();
return true;
} catch (IOException | NullPointerException e) {
return false;
}
}

public List<String> checkMatches(String fileName, String suffix)
throws IOException {
List<String> matches = new ArrayList<>();

InputStream is = CharsFinder.class.getClassLoader()
.getResourceAsStream(fileName);
BufferedReader bf = new BufferedReader(new InputStreamReader(is));
String line = "";
while ((line = bf.readLine()) != null) {
if (line.endsWith(suffix)) {
matches.add(line);
}
}

return matches;
}

public static void main(String[] args) throws IOException {
CharsFinder cf = new CharsFinder();
final Scanner reader;
List<String> matches = new ArrayList<>();
String fileName;
reader = new Scanner(System.in);
do {
System.out.println("Ingrese el fichero a buscar");
fileName = reader.next();
if (cf.checkExt(fileName)) {
System.out.println("Ingrese la terminación que desea buscar");
String suffix = reader.next();
matches = cf.checkMatches(fileName, suffix);
} else {
System.out.println("El fichero debe tener extensión .txt");
}
} while (!fileName.endsWith(".txt"));
reader.close();

if (!matches.isEmpty()) {
for (String coincidence : matches) {
System.out.println(coincidence);
}
} else {
System.out.println("No se encontraron coincidencias");
}
}
}

Junio 18, 2015, 10:52:23 AM #2 Ultima modificación: Junio 18, 2015, 12:24:55 PM por elmoyer
Gracias por responder compañero. Pero podrías explicarme  como funciona un poco el Charsfinder?
Porq cuando lo ejecuto puedo escribir "blablabla.txt" y luego me pregunta por el sufijo pero si no existe el archivo blablabla.txt no tendría que pedirme el sufijo ya que no puede trabajar con un archivo que no existe.

El chatreader lo he hecho en otro archivo:

Código: php
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
 

public class ChatReader {
 

    private String fileName;
 
    public ChatReader(String fileName) {
        this.setFileName(fileName);
    }
     
    public String[] getMessages() {
        try {
            // path to the chat log file
            Path p = Paths.get(this.getFileName());
            // read all lines and store them in a list
            List<String> lines = Files.readAllLines(p, Charset.forName("UTF-8"));
            String[] messages =
                    lines.toArray(new String[lines.size()]);
            return messages;
        } catch (IOException e) {
            System.err.println("Couldn't read " + this.getFileName() + "\n Did you give me the correct path?");
        }
        return new String[]{};
    }
 
 
    public String getFileName() {
        return fileName;
    }
 
 
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
 
}



Para el contador de frecuencia de una palabra he escrito esto, pero me gustaría saber si alguien tiene una forma mas fácil(que no implique por ejemplo tener que hacer un reverse para que primero vayan los mas frecuentes):

Código: php
//frequency count :
for (String type:tokenS){ //for each word our list of tokens
Double oldCounter = typeFreq.get(type); //oldCounter's value is the value of the key 'type'
if (oldCounter == null){ //check if there is no value in the map
oldCounter = 0.; //reset : oldCounter has the value 0 (dot because it is a double)
}
typeFreq.put(type, ++oldCounter); //add the current word and its counter +1
//if the counter was 0, we have oldCounter=1
//and if the counter for that type already had a value>0 : +1.

//as we cannot have duplicate keys in a map, it will always go to the already existing entry
//if the current word already appeared before.
}

System.out.println(typeFreq.toString()); //problem : does not print special characters : ü,ö,ä,... (->replace?)

double temp=0; //current value
double max=0; //biggest current value
for(String key:typeFreq.keySet()){ //for each key (token)
temp=typeFreq.get(key); //hold its value (frequency)
if(temp>=max){ //if value bigger than max
max=temp; //value is the new max
//System.out.println(key); //print corresponding key
//that way we print the key with the smallest value first
toBeReversed.add(key);
continue;
}
}
Collections.reverse(toBeReversed);
System.out.println(toBeReversed.toString());
return " ";
}

}


Un saludo!  ;D

1. El método checkExt, verifica si la extensión es válida (.txt).
2. El método exists verifica si el archivo existe en el folder src.
3. El método checkMatches recorre el archivo en busca de las líneas con la extensión especificada.

El flujo es el siguiente:

1. Pide el nombre del archivo.
    1.2 Verifica si tiene extensión .txt
2. Comprueba que el archivo exista.
3. Si punto 2 retorna true, pide extensión a buscar.
4. Recorre el archivo en busca de líneas que terminen con dicha extensión.

Código: java

CharsFinder cf = new CharsFinder();
final Scanner reader;
List<String> matches = new ArrayList<>();
String fileName;
reader = new Scanner(System.in);
do {
System.out.println("Ingrese el fichero a buscar");
fileName = reader.next();
// si la extensión es correcta
if (cf.checkExt(fileName)) {
// si el archivo existe
if(cf.exists(fileName)) {
System.out.println("Ingrese la terminación que desea buscar");
String suffix = reader.next();
matches = cf.checkMatches(fileName, suffix);
}
// caso contrario salimos del programa
else {
System.out.println("El archivo no existe");
System.exit(-1);
}
}
// la extension no es .txt
else {
System.out.println("El fichero debe tener extensión .txt");
}
} while (!fileName.endsWith(".txt"));
reader.close();

if (!matches.isEmpty()) {
for (String coincidence : matches) {
System.out.println(coincidence);
}
} else {
System.out.println("No se encontraron coincidencias");
}


En caso quieras buscar palabras, solo debes hacer:

Código: java
String[] words = line.split(" ");
for(String word : words) {
    if(word.endsWith(".txt")) { matches.add(word); }
}