Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Read file and extract different tokens

  1. #1
    Member
    Join Date
    Jul 2012
    Location
    Spain
    Posts
    42
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Read file and extract different tokens

    I'm getting mad, I made a code that is very bad for maintain and for read.... please help
    I am beginner with these classes that I am using, and I maybe missed an unknown methods for do my code easier...

    I need some help for use another ways to extract strings easier that I did.
    What i have to do:

    It is a menu with 3 options:
    1: add a name of a person, and a date , the file must contain the name in a new line, and the date in a new line ( like below):
    Rexshine
    21/2/2001
    Norm
    21/2/2000

    2: read the file with data output like this:
    [code=java]System.out.println("The birthday of "+ name +" is the day "+ day+" del "+ month +" (nació en el año "+ year +")");

    3: exit

    My solution (don't know easier, help):

    maybe is easier to read the java code than read to my english


    - For extract the name i make a split of \n of the file, and get it into a vector
    once i do so, i do a split of the vector every 2 elements, so I do again an split "/" of every date, and get it into an array of ints, so i can fill a variable int "day", another "month" and other "year", and still have the vector with strings so i can fill "name"

    I didn't finish of implement it, because i get error. so, any help is grateful

    I get error in line 168, i know what i do wrong but can't fix, i don't think that is so hard to do it better, than fix what i'm triying to do. correct me please.

    import java.io.EOFException;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.FileWriter;
    import java.io.FileReader;
    import java.util.StringTokenizer;
    import java.util.Vector;
     
     
    public class Birthday {
     
    	static final int LINEAS = 1;
     
    	static final int NUEVO_CUMP = 1;
    	static final int CONSULTAR = 2;
    	static final int SALIR = 3;
     
    	public static void main(String[] args) {
    		menu();
    	}
    	static void menu(){
    		try{
    			BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
    			int opcion;
     
    			/** NEW CODE FOR NORM, I CREATE THE FILE .txt AUTO*/
                            File file= new File("birth.txt");
    			String fichero = file.getName();
    			/* MY REAL-CODE
                            do{
    				System.out.println("insert the name of the file");
    				fichero = lector.readLine();
    				if(!(new File(fichero).exists()))
    					System.err.println("file no exists.");
    			}while(!(new File(fichero).exists()));
    			*/
    			//Control de la salida del menú
    			do{
    				//options
    				do{
     
    					limpia();
     
    					limpia();
    					System.out.println(NUEVO_CUMP+".ADd new birthday.");
    					System.out.println(CONSULTAR+". Get birthdays from file.");
    					System.out.println(SALIR+". Exit");
    					opcion = Integer.parseInt(lector.readLine());
    				}while(opcion != NUEVO_CUMP && opcion != CONSULTAR && opcion != SALIR);
     
    				switch(opcion){
    					case NUEVO_CUMP:
    						//Se piden los datos
    						System.out.println("write the name of the guy that you want to add:");
    						String cumpleaños = lector.readLine();
    						System.out.println("write new birth you want to add (format day/month/year):");
    						cumpleaños += "/"+lector.readLine();
     
    						//Llamada al método.
    						nuevoCumpleaños(fichero, cumpleaños);
     
    						//Se sostiene la pantalla
    						System.out.println("Press a key to continue.");
    						lector.readLine();
    						break;
    					case CONSULTAR:
     
    						muestraCumpleaños(fichero);
     
    						//Se sostiene la pantalla
    						System.out.println("Press a key to continue.");
    						lector.readLine();
    						break;
    					case SALIR:
    						System.out.println("Normal exit.");
    				}
     
    			}while(opcion != SALIR);
    		}catch(NumberFormatException e){
    			System.err.println("Error. number expected.");
    		}catch(IOException e){
    			System.err.println("Error R/W.");
    		}catch(Exception e){
    			System.err.println("Error. ");
    		}
    	}
    // METHOD NOT SO GOOD, BUT WORKS
    	static void nuevoCumpleaños(String fichero, String datos) throws IOException{
     
    		String nombre;
    		int dia;
    		int mes;
    		int año;
     
    		try{
    			FileWriter escritor = new FileWriter(fichero, true);
     
    			String[] array = datos.split("/"); 
     
    			nombre = array[0];
    			dia = Integer.parseInt(array[1]);
    			mes = Integer.parseInt(array[2]);
    			año = Integer.parseInt(array[3]);
    			System.out.println("array[3]"+Integer.parseInt(array[3])+" y "+array[3]);
     
    			//Formato datos del fichero:
    			escritor.write("\n"+nombre+"\n");
    			escritor.write(dia+"/");
    			escritor.write(mes+"/");
    			escritor.write(año+" ");
     
     
    			escritor.flush();
    			escritor.close();
    		}catch(EOFException e){
    			System.err.println("file not found.");
    		}
    	}
     
    //METHOD NOT SO GOOD
    	static void muestraCumpleaños(String fichero) throws IOException{
    		try{
    						BufferedReader lectorArchivo = new BufferedReader(new FileReader(fichero));
     
    			Vector<String> dato = new Vector<String>();
    			String lin = "";
    			StringTokenizer st = new StringTokenizer("/");
    			while((lin = lectorArchivo.readLine()) != null){
    				dato.add(lin);
    				//System.out.println(lin);
    			}
    			String[] nombreArray = new String[(dato.size()/2)+1];
     
    			int[] dia = new int[((dato.size()/2)+1)/3];
    			int[] mes = new int[((dato.size()/2)+1)/3];
    			int[] año = new int[((dato.size()/2)+1)/3];
     
    			String[] fecha = null ;
    			for(int i=0, j=1, k=2; i<dato.size() ;i++, j+=2, k+=2){
    				nombreArray[i] = dato.elementAt(j);
    				fecha = new String[dato.size()/2];
    				fecha = dato.elementAt(k).toString().split("/");
    			}
    			for(int i=0, j=1, k=2; k<fecha.length ;i+=3, j+=3, k+=3){
    				dia[i] = Integer.parseInt(fecha[i]);
    				mes[i] = Integer.parseInt(fecha[j]);
    				año[i] = Integer.parseInt(fecha[k]);
    			}
    			for(int i=0; i<nombreArray.length ;i++){
    				System.out.println("Birthday of "+nombreArray[i]+" is the day "+dia[i]+" month: "+mes[i]+" (has born in... "+año[i]+")");	
    			}
     
    			lectorArchivo.close();
     
    		}catch(FileNotFoundException e){
    			System.err.println();
    		}
    	}
    	static void limpia (){
    		for(int i=0; i<LINEAS ;i++)
    			System.out.println();
    	}
    }


    Thank you in advance.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Read file and extract different tokens

    I get error in line 168,
    Please copy the full text of the error message and paste it here.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Jul 2012
    Location
    Spain
    Posts
    42
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Read file and extract different tokens

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 >= 7
    at java.util.Vector.elementAt(Unknown Source)
    at Ejercicio07.muestraCumpleaños(Birthday.java:164)
    at Ejercicio07.menu(Ejercicio07.java:98)
    at Ejercicio07.main(Ejercicio07.java:50)


    but i control it with try catch

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Read file and extract different tokens

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 >= 7
    at java.util.Vector.elementAt(Unknown Source)
    at Ejercicio07.muestraCumpleaños(Birthday.java:164)
    The code at line 164 used an index past the end of the array.
    Remember that array indexs range from 0 to the array length-1

    A suggestion for easier testing and to make sure all testers are using the same data.
    Use the StringReader class with a String that contains all the responses that the program will read.
    Here is a sample of how to use it:
             StringReader sr = new StringReader("1\nJuan\n12/12/1912\n3\n\n");  //  put responses here
    	 BufferedReader lector = new BufferedReader(sr); //new InputStreamReader(System.in));
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Jul 2012
    Location
    Spain
    Posts
    42
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Read file and extract different tokens

    Quote Originally Posted by Norm View Post
    A suggestion for easier testing and to make sure all testers are using the same data.
    Use the StringReader class with a String that contains all the responses that the program will read.
    Here is a sample of how to use it:
             StringReader sr = new StringReader("1\nJuan\n12/12/1912\n3\n\n");  //  put responses here
    	 BufferedReader lector = new BufferedReader(sr); //new InputStreamReader(System.in));
    what do you mean with "put responses here", you mean i catch the response of the method that fill the file into a string? so i transfer it to the method that reads the file?
    anyway i don't understand for what.

    by the way, i didn't use never StringReader

    thank you.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Read file and extract different tokens

    what do you mean with "put responses here",
    Using the StringReader class as I suggest saves everyone from entering test data with the keyboard.
    The "responses" are what you type into the console with the keyboard when you execute the program for testing.
    Put everything you would type into the keyboard in the String in the StringReader's constructor as I have shown.
    Compile and execute the program and there will be nothing to type in when testing.

    You need to add lots of println statements to the code to see what it is doing in the muestraCumpleaños() method.
    Print out the values of all the variables used there. Especially in the loops
    If you don't understand my answer, don't ignore it, ask a question.

  7. The Following User Says Thank You to Norm For This Useful Post:

    Rexshine (February 23rd, 2013)

  8. #7
    Member
    Join Date
    Jul 2012
    Location
    Spain
    Posts
    42
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Read file and extract different tokens

    Thank you for StringReader sugestion, I'm using henceforth.

    Okay i will fix it tomorrow what I'm trying to do, since you don't tell me is bad. But there isn't just a faster way? a method to read a file line with a pattern?

  9. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Read file and extract different tokens

    a method to read a file line with a pattern?
    There are several classes for regular expressions. Look at the java.util.regex package.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #9
    Member
    Join Date
    Jul 2012
    Location
    Spain
    Posts
    42
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Read file and extract different tokens

    Impossible to understand anything java.util.regex ^^,(only understood \\s+ pattern) . Thank you for today. Ill try to finish tomorrow my program with my "println" knowledge

  11. #10
    Member
    Join Date
    Sep 2012
    Posts
    128
    Thanks
    1
    Thanked 14 Times in 14 Posts

    Default Re: Read file and extract different tokens

    There's quite a complex part of your code that processes the date text. Have you thought about using SimpleDateFormat? (SimpleDateFormat (Java Platform SE 7 ))

  12. #11
    Member
    Join Date
    Jul 2012
    Location
    Spain
    Posts
    42
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Read file and extract different tokens

    Quote Originally Posted by Starstreak View Post
    There's quite a complex part of your code that processes the date text. Have you thought about using SimpleDateFormat? (SimpleDateFormat (Java Platform SE 7 ))
    will take a look to SimpleDateFormat examples. Thanks

Similar Threads

  1. extract selected text out of a pdf file using java
    By ashish.sharma in forum What's Wrong With My Code?
    Replies: 5
    Last Post: December 2nd, 2013, 04:01 AM
  2. NEED TO EXTRACT FROM CSV FILE PUT INTO JTEXTFIELDS (JAVA SWING GUI)
    By Harry998 in forum What's Wrong With My Code?
    Replies: 13
    Last Post: February 20th, 2013, 11:24 AM
  3. Binary File. Extract float data from binary file and put into array
    By cardinal152 in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: June 13th, 2012, 07:31 PM
  4. Extract the file path
    By sanvica in forum AWT / Java Swing
    Replies: 2
    Last Post: March 30th, 2012, 12:01 PM
  5. Extract data from a file
    By kafka82 in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: September 1st, 2011, 03:02 AM