Buscar
Social
Ofertas laborales ES
« Java 7: leyendo ficheros indicando el encoding | Main | Eclipse anuncia la versión 9.0 de Orion »
miércoles
ago122015

Java 7: ejemplos prácticos

1: Switch permite tomar tipos Strings como argumentos:
01.public stringsEnCase(Trade t) {
02.  
03.            String status = t.getStatus();
04.  
05.            switch(status) {
06.  
07.            caseNEW:
08.  
09.                  newTrade(t);
10.  
11.                  break;
12.  
13.            caseEXECUTE:
14.  
15.                  executeTrade(t);
16.  
17.                  break;
18.  
19.            casePENDING:
20.  
21.                  pendingTrade(t);
22.  
23.                  break;
24.  
25.  
26.  
27.            default:
28.  
29.                  break;
30.  
31.            }
32.  
33.      }
2: Gestión automática de recursos
01.public voidnewTry() {
02. 
03.           try(FileOutputStream fos = newFileOutputStream("movies.txt");
04. 
05.                       DataOutputStream dos = newDataOutputStream(fos)) {
06. 
07.                 dos.writeUTF("Java 7 yeah");
08. 
09.           } catch(IOException e) {
10. 
11.                 // log the exception
12. 
13.           }
14. 
15.     }
3: Literales numéricos con barra baja
1.int million  =  1_000_000
4: Mejorado el manejo de excepciones
01.public voidnewMultiCatch() {
02. 
03.           try{
04. 
05.                 methodThatThrowsThreeExceptions();
06. 
07.           } catch(ExceptionOne | ExceptionTwo | ExceptionThree e) {
08. 
09.                 // log and deal with all Exceptions
10. 
11.           }
12. 
13.     }
5: Nuevas apis de fichero
01.package java7;
02. 
03.import java.io.File;
04.import java.io.FileOutputStream;
05.import java.io.IOException;
06.import java.io.OutputStream;
07.import java.nio.file.Files;
08.import java.nio.file.Path;
09.import java.nio.file.Paths;
10. 
11.public class PruebasDeFichero {
12. 
13.    public void pruebas() {
14. 
15.        Path pathOrigen = Paths.get("c:\\Temp\\tempOrigen");
16. 
17.        System.out.println("Número de nodos:" + pathOrigen.getNameCount());
18. 
19.        System.out.println("Nombre de fichero:" + pathOrigen.getFileName());
20. 
21.        System.out.println("Raíz:" + pathOrigen.getRoot());
22. 
23.        System.out.println("Padre:" + pathOrigen.getParent());
24. 
25.        OutputStream fis;
26.        try {
27.            fis = new FileOutputStream(new File(
28.                    "c:\\Temp\\temp2\\holaMundo2.txt"));
29. 
30.            Files.copy(pathOrigen, fis);
31.            Path pathOrigenDestino = Paths.get("c:\\Temp\\tempDestino");
32.            Files.move(pathOrigen, pathOrigenDestino);
33. 
34.        } catch (IOException e) {
35.            // TODO Auto-generated catch block
36.            e.printStackTrace();
37.        }
38. 
39.        try {
40.            Files.delete(pathOrigen);
41.        } catch (IOException e) {
42.            // TODO Auto-generated catch block
43.            e.printStackTrace();
44.        }
45.        try {
46.            Files.deleteIfExists(pathOrigen);
47.        } catch (IOException e) {
48.            // TODO Auto-generated catch block
49.            e.printStackTrace();
50.        }
51. 
52.    }
53.}
6: Escucha activa de eventos sobre ficheros
01./**
02.  
03. * This initiates the police
04.  
05. */
06.  
07.private voidinit() {
08.  
09.      path= Paths.get("C:\Temp\temp\");
10.  
11.      try{
12.  
13.            watchService= FileSystems.getDefault().newWatchService();
14.  
15.            path.register(watchService, ENTRY_CREATE, ENTRY_DELETE,
16.  
17.                        ENTRY_MODIFY);
18.  
19.      } catch(IOException e) {
20.  
21.            System.out.println("IOException"+ e.getMessage());
22.  
23.      }
24.  
25.}
26.  
27./**
28.  
29. * The police will start making rounds
30.  
31. */
32.  
33.private voiddoRounds() {
34.  
35.      WatchKey key = null;
36.  
37.      while(true) {
38.  
39.            try{
40.  
41.                  key = watchService.take();
42.  
43.                  for(WatchEvent<!--?--> event : key.pollEvents()) {
44.  
45.                        Kind<!--?--> kind = event.kind();
46.  
47.System.out.println("Event on "+ event.context().toString() + " is " + kind);
48.  
49.                  }
50.  
51.            } catch(InterruptedException e) {
52.  
53.System.out.println("InterruptedException: "+e.getMessage());
54.  
55.            }
56.  
57.            booleanreset = key.reset();
58.  
59.            if(!reset)
60.  
61.                  break;
62.  
63.      }
64.  
65.}
7: Tareas recursivas
001.package forkJoinDemoEjemploAsíncrono;
002.  
003.import java.io.File;
004.import java.util.ArrayList;
005.import java.util.List;
006.import java.util.concurrent.RecursiveTask;
007.  
008.public class ProcesadorDeDirectorios extends RecursiveTask<list<string>>
009.{
010.   private static final long serialVersionUID = 1L;
011.   //El path que será procesado
012.   private final String      path;
013.   //Extensión de ficheros en cuestión
014.   private final String      extension;
015.  
016.   //Constructor
017.   public FolderProcessor(String path, String extension)
018.   {
019.      this.path = path;
020.      this.extension = extension;
021.   }
022.  
023.   //Implementación del método compute, que debe devolver un listado de Strings, pues aśi fue parametrizado RecursiveTask
024.   @Override
025.   protected List<string> compute()
026.   {
027.      //La lista de los nombres de los ficheros almacenados en el directorio
028.      List<string> list = new ArrayList<string>();
029.      //Tareas que almacenan las subtareas que van a procesar los subdirectorios almacenados
030.      //en el directorio padre
031.      List<folderprocessor> tasks = new ArrayList<folderprocessor>();
032.      //Obtiene el contenido del directorio
033.      File file = new File(path);
034.      File content[] = file.listFiles();
035.      //Para cada elemento del directorio, si hay un subdirectorio, cra un objeto FolderProcessor
036.      if (content != null)
037.      {
038.         for (int i = 0; i < content.length; i++)
039.         {
040.            if (content[i].isDirectory())
041.            {
042.               FolderProcessor task = new FolderProcessor(content[i].getAbsolutePath(), extension);
043.               task.fork();
044.               tasks.add(task);
045.            }
046.            //Otherwise, compare the extension of the file with the extension you are looking for using the checkFile() method
047.            //En otro caso, compara la extensión del fichero con la que se busca (definida
048.            //en el método checkfile()
049.            else
050.            {
051.               if (checkFile(content[i].getName()))
052.               {
053.                  list.add(content[i].getAbsolutePath());
054.               }
055.            }
056.         }
057.      }
058.      //Si el listado de tareas de FolderProcesar supera los 50 elementos, se muestra un mensaje
059.      //por consola
060.      if (tasks.size() > 50)
061.      {
062.         System.out.printf("%s: %d Tareas ejecutadas.\n", file.getAbsolutePath(), tasks.size());
063.      }
064.      //Añade a la lista de ficheros los resultados returnados por las subtareas ejecutadas en
065.      //esta tarea
066.      addResultsFromTasks(list, tasks);
067.      //Retorna el listado de strings.
068.      return list;
069.   }
070.  
071.   //Para cada tarea almacenada en la lista de tareas, llama al método join() que esperará
072.   //a la finalización y retornará entonces el resultado de las tareas.
073.   private void addResultsFromTasks(List<string> list, List<folderprocessor> tasks)
074.   {
075.      for (FolderProcessor item : tasks)
076.      {
077.         list.addAll(item.join());
078.      }
079.   }
080.  
081.   //Compara si el nombre del fichero pasado como parámetro tiene como extensión la que buscamos
082.   private boolean checkFile(String name)
083.   {
084.      return name.endsWith(extension);
085.   }
086.}
087. 
088.package forkJoinDemoAsyncExample;
089.  
090.import java.util.List;
091.import java.util.concurrent.ForkJoinPool;
092.import java.util.concurrent.TimeUnit;
093.  
094.public class Main
095.{
096.   public static void main(String[] args)
097.   {
098.      //Crea el pool fork join usando el constructor por defecto.
099.      ForkJoinPool pool = new ForkJoinPool();
100.      //Crea tres tareas FolderProcessor. Inicializa cada una de ellas con un path
101.      //de directorio diferente
102.      FolderProcessor system = new FolderProcessor("C:\\Windows", "log");
103.      FolderProcessor apps = new FolderProcessor("C:\\Program Files", "log");
104.      FolderProcessor documents = new FolderProcessor("C:\\Documents And Settings", "log");
105.      //Ejecuta las tres tareas en el pool mediante el método execute.
106.      pool.execute(system);
107.      pool.execute(apps);
108.      pool.execute(documents);
109.      //Escribe a la consola información sobre el estado del pool cada segunda, hasta que
110.      //las tres tareas han finalizado su ejecución
111.      do
112.      {
113.         System.out.printf("******************************************\n");
114.         System.out.printf("Main: Paralelismo: %d\n", pool.getParallelism());
115.         System.out.printf("Main: Hilos activos: %d\n", pool.getActiveThreadCount());
116.         System.out.printf("Main: Contados de tareas: %d\n", pool.getQueuedTaskCount());
117.         System.out.printf("******************************************\n");
118.         try
119.         {
120.            TimeUnit.SECONDS.sleep(1);
121.         } catch (InterruptedException e)
122.         {
123.            e.printStackTrace();
124.         }
125.      } while ((!system.isDone()) || (!apps.isDone()) || (!documents.isDone()));
126.      //Para el pool de fork join
127.      pool.shutdown();
128.      //Escribe el número de resultados generados por cada tarea a la consola
129.      List<string> results;
130.      results = system.join();
131.      System.out.printf("System: %d ficheros encontrados.\n", results.size());
132.      results = apps.join();
133.      System.out.printf("Apps: %d ficheros encontrados.\n", results.size());
134.      results = documents.join();
135.      System.out.printf("Documents: %d ficheros encontrados.\n", results.size());
136.   }
137.}
138.</string></folderprocessor></string></folderprocessor></folderprocessor></string></string></string></list<string>

Muchas gracias,

Un saludo

PrintView Printer Friendly Version

EmailEmail Article to Friend

References (1)

References allow you to track sources for this article, as well as articles that were written in response to this article.

Reader Comments (4)

Dejo 2 para no hacer muy largo el comentario:

1. Inyección de dependencias


@Qualifier
@Retention(RUNTIME)
@Target({FIELD, METHOD, PARAMETER, TYPE})
public @interface PostgreSQL {}


@Qualifer
@Retention(RUNTIME)
@Target({FIELD, METHOD, PARAMETER, TYPE})
public @interface MySQL {}


public interface IConnection {
Connection getConection();
}


@PostgreSQL
public class PostgreSQLConnection implements IConnection {

@Override
public Connection getConnection() throws SQLException {
Class.forName("org.postgresql.Driver");
return DriverManager.getConnection("jdbc:postgresql://localhost:5432/bbdd",
"useer", "pass");
}
}


@MySQL
public class MySQLConnection implements IConnection {

@Override
public Connection getConnection() throws SQLException {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/bbdd",
"useer", "pass");
}
}


@Stateless
@LocalBean
public class ItemEJB {

@Inject @PostgreSQL
private Connection conn;
}


2. Produces y Disposes


@Qualifier
@Rentention(RUNTIME)
@Target({FIELD, METHOD, PARAMETER, TYPE})
public @interface Connection {
ConnectionType type();
String host();
String port();
String database();
String user();
String pass();

public enum ConnectionType {
MYSQL, POSTGRESQL, ORACLE, DERBY;
}
}


public class ConnectionProducer {

@Produces @Connection
public Connection connection(InjectionPoint ip) throws SQLException {

Annotated annotated = ip.getAnnotated();
Annotation annotation = annotated.getAnnotation(Connection.class); // del qualifier
ConnectionType connType = annotation.type(); // obtiene el tipo de conexión elegido

// propiedades de la conexión
String host = annotation.host();
String port = annotation.port();
String database = annotation.database();
String user = annotation.user();
String pass = annotation.pass();

String connUri;

switch(connType) {
case ConnectionType.MYSQL:
String connUri = "jdbc:mysql://" + host + ":" + port + "/" + database;
Class.forName("com.mysql.jdbc.Driver");
break;
case ConnectionType.POSTGRESQL:
String connUri = "jdbc:postgresql://" + host + ":" + port + "/" + database;
Class.forName("org.postgresql.Driver");
break;
case ConnectionType.ORACLE:
String connUri = "jdbc:oracle:thin:@" + host + ":" + port + ":" + database;
Class.forName("org.postgresql.Driver");
break;
case ConnectionType.DERBY:
String connUri = "jdbc:derby://" + host + "/" database;
}

return DriverManager.getConnection(connUri, user, pass);
}

public void closeConnection(@Disposes @Connection Connection conn) throws SQLException {
conn.close();
}
}


@Stateless
@LocalBean
@RequestScoped
public class ItemEJB {

@Inject @Connection(
host = "127.0.0.1",
port = "5432",
database = "NasaDB",
user = "root",
pass = "toor",
ConnectionType.POSTGRESQL
)
private Connection connection;

...
}

DI gist
Producer/Disposer gist

agosto 12, 2015 | Unregistered CommenterMitsu Gami

lo de la escucha a ficheros esta interesante
y lo de tareas re cursivas esta super util para hacer tareas pesadas de manera rápida
pero es bien raro párese que no sirve pero si lo intentas con varios cores mas memoria con volumen de procesamiento grande y con un thr@1171@lot alto si reduce casi a mas de la mitad sin esfuerso

agosto 12, 2015 | Unregistered Commenterluis

Aquí tenéis un post "más o menos" con los mismos ejemplos explicados.
http://radar.oreilly.com/2011/09/java7-features.html

agosto 13, 2015 | Unregistered Commenteralvaro

Gracias Álvaro, en efecto, es el post original.
Lo incluyo en fuentes (References, al final del artículo). pensé que ya lo había hecho). ¡Mis disculpas!

agosto 19, 2015 | Registered Commenterjcarmonaloeches

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>