12.07.2015 Views

Desarrollo de proyectos informáticos con tecnología Java

Desarrollo de proyectos informáticos con tecnología Java

Desarrollo de proyectos informáticos con tecnología Java

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

8.1. LA CLASE SCANNER 1192627 }Listado 8.1: Lectura <strong>de</strong> líneas <strong>de</strong> texto <strong>de</strong>s<strong>de</strong> un fichero <strong>con</strong> el uso <strong>de</strong> la claseScannerLa clase Scanner tiene métodos para po<strong>de</strong>r leer tipos <strong>de</strong> datos primitivostal y como se muestra en el Listado 8.2.1 package u t i l i d a d ;23 import j a v a . i o . F i l e ;4 import j a v a . i o . FileNotFoundException ;5 import j a v a . u t i l . Scanner ;67 public f i n a l c l a s s U t i l i d a d S c a n n e r 2 {8 private s t a t i c f i n a l S t r i n g FICHERO = " a g e n d a . txt " ;910 private U t i l i d a d S c a n n e r 2 ( ) {11 super ( ) ;12 }1314 private void e j e c u t a ( ) {15 try {16 Scanner s c a n n e r = new Scanner (new F i l e (FICHERO) ) ;17 while ( s c a n n e r . hasNext ( ) ) {18 a n a l i z a L i n e a ( s c a n n e r . nextLine ( ) ) ;19 }20 } catch ( FileNotFoundException e ) {21 e . p r i n t S t a c k T r a c e ( ) ;22 }23 }2425 private void a n a l i z a L i n e a ( S t r i n g l i n e a ) {26 Scanner s c a n n e r = new Scanner ( l i n e a ) ;27 s c a n n e r . u s e D e l i m i t e r ( " : " ) ;28 S t r i n g persona , nombre , a p e l l i d o s ;29 int t e l e f o n o ;30 persona = s c a n n e r . next ( ) ;31 nombre = s c a n n e r . next ( ) ;32 a p e l l i d o s = s c a n n e r . next ( ) ;33 t e l e f o n o = s c a n n e r . n e x t I n t ( ) ;34 System . out . p r i n t l n ( nombre + " , " + a p e l l i d o s + " , " + t e l e f o n o ) ;35 }3637 public s t a t i c void main ( S t r i n g a r g s [ ] ) {38 new U t i l i d a d S c a n n e r 2 ( ) . e j e c u t a ( ) ;39 }40 }Listado 8.2: Lectura <strong>de</strong> líneas <strong>de</strong> texto <strong>de</strong>s<strong>de</strong> un fichero <strong>con</strong> el uso <strong>de</strong> la claseScannerEl resultado <strong>de</strong> la ejecución <strong>de</strong> este código es el siguiente:FRANCISCO JOSE,ALVAREZ MARTIN,90727037ROBERTO,CASTRO RUIZ,945953372MANUEL,PEREZ HERRERA,520908284JULIA,ALVAREZ ORTEGA,482596843TOMAS,VARGAS MARTINEZ,691825532Si <strong>con</strong>struimos la instancia <strong>de</strong> Scanner sobre el flujo <strong>de</strong> bytes que representaal teclado System.in, <strong>con</strong> la clase Scanner podremos leer tipos <strong>de</strong> datosprimitivos, tal y como muestra el Listado 8.3.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!