Test Foro de elhacker.net SMF 2.1

Programación => Programación General => Java => Mensaje iniciado por: LaThortilla (Effort) en 17 Noviembre 2016, 02:01 AM

Título: Ayuda leyendo archivo de 5 GB [OutOfMemoryError]
Publicado por: LaThortilla (Effort) en 17 Noviembre 2016, 02:01 AM
Buenos dias estoy teniendo problemas para generar un script que me permita almacenar una base de datos que esta en un txt separando cada registro por lineas y cada columna por comas..



estoy intentando guardar estos registros en una base de datos mysql pero dado que es tan grande el archivo me esta generando un error:


Código (java) [Seleccionar]

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOfRange(Arrays.java:2694)
at java.lang.String.<init>(String.java:203)
at java.nio.HeapCharBuffer.toString(HeapCharBuffer.java:561)
at java.nio.CharBuffer.toString(CharBuffer.java:1201)
at java.util.regex.Matcher.toMatchResult(Matcher.java:249)
at java.util.Scanner.match(Scanner.java:1339)
at java.util.Scanner.hasNextLine(Scanner.java:1547)
at testproject.TestProject.main(TestProject.java:90)
Java Result: 1



les pongo el codigo completo por si alguien se le ocurre como solucionarlo....

Código (java) [Seleccionar]
package testproject;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
*
* @author Usuario
*/
public class TestProject {
   /**
    * @param args the command line arguments
    */
   
   public static Connection con;
    public static void conectar() {
       try {
         
           if (con == null || con.isClosed()) {
               String connection = "jdbc:mysql://" + "localhost" + ":" + "3306" + "/" + "base";
               String user = "aaa";
               String password = "***";
               con = DriverManager.getConnection(connection, user, password);
               System.out.println("");
               //System.out.println("[*][SQL] Conexión Exitosa.");
           }
       } catch (SQLException ex) {
           ex.printStackTrace();
           System.out.println("[Error][SQL] No se pudo crear conexión con la base de datos.");
       }

   }
   
    public static void printLog(String line){
           FileWriter outputStream = null;
       try {
           outputStream = new FileWriter("errlog.txt",true);
           PrintWriter pw = new PrintWriter(outputStream);
           pw.println(line);
           pw.close();
           
       } catch (IOException ex) {
           Logger.getLogger(TestProject.class.getName()).log(Level.SEVERE, null, ex);
       }
           
    }
   public static void main(String[] args) throws FileNotFoundException, SQLException, IOException {
       String driver = "com.mysql.jdbc.Driver";
       try {
           Class.forName(driver);
       } catch (ClassNotFoundException ex) {
       }
       conectar();
       FileInputStream inputStream = null;
     
       Scanner sc = null;
       try {
           inputStream = new FileInputStream("C:\\Users\\usuario\\Desktop\\base5GB.txt");
         

         
           sc = new Scanner(inputStream, "UTF-8");
           while (sc.hasNextLine()) {
               String line = sc.nextLine();
               try{
                   if(line.length() > 2){
                       String [] campos = line.split(",");
                       if(campos.length == 10){
                           String QUERY = "INSERT INTO `tabla`(`campo1`, `campo2`,`campo3`, `campo4`, `campo5`, `campo6`, `campo7`, `campo8`, `campo9`, `campo10`) VALUES ("+campos[0]+",'"+campos[1]+"','"+campos[2]+"','"+campos[3]+"','"+campos[4]+"','"+campos[5]+"','"+campos[6]+"','"+campos[7]+"','"+campos[8]+"','"+campos[9]+"')";
                           PreparedStatement prest = con.prepareStatement(QUERY);
                           if(prest.executeUpdate()>0){
                               System.out.println("ID Insertado  "+campos[0]);
                            }else{
                                printLog(line);
                           }
                       }else{
                            printLog(line);
                       }
                   }else{

                    //System.out.println("ID Insertado"+idBD);
                   }
               // System.out.println(line);
               }catch(Exception ex){
                   System.out.println("-"+line+"-");
                   ex.printStackTrace();
                   printLog(line);
               }
           }
           // note that Scanner suppresses exceptions
           if (sc.ioException() != null) {
               throw sc.ioException();
           }
       } finally {
           if (inputStream != null) {
               inputStream.close();
           }
           if (sc != null) {
               sc.close();
           }
       }
   }
   
}

Título: Re: Ayuda leyendo archivo de 5 GB [OutOfMemoryError]
Publicado por: engel lex en 17 Noviembre 2016, 02:15 AM
no se java... pero no puedes ir leyendo por secciones e ir liberando la memoria de la sección leida?
Título: Re: Ayuda leyendo archivo de 5 GB [OutOfMemoryError]
Publicado por: LaThortilla (Effort) en 17 Noviembre 2016, 03:32 AM
Si eso es lo que estoy buscando y estoy probando con

Código (java) [Seleccionar]
System.cg();

no se si funcionara....
Título: Re: Ayuda leyendo archivo de 5 GB [OutOfMemoryError]
Publicado por: Konlex en 17 Noviembre 2016, 03:51 AM
Encontre una posible solucion: Click aqui (https://examples.javacodegeeks.com/java-basics/exceptions/java-lang-outofmemoryerror-how-to-solve-outofmemoryerror/)

saludos!
Título: Re: Ayuda leyendo archivo de 5 GB [OutOfMemoryError]
Publicado por: LaThortilla (Effort) en 17 Noviembre 2016, 04:15 AM
Cita de: Konlex en 17 Noviembre 2016, 03:51 AM
Encontre una posible solucion: Click aqui (https://examples.javacodegeeks.com/java-basics/exceptions/java-lang-outofmemoryerror-how-to-solve-outofmemoryerror/)

saludos!

No es la solución pero me ayuda a monitorear  la memoria disponible...
Título: Re: Ayuda leyendo archivo de 5 GB [OutOfMemoryError]
Publicado por: Konlex en 17 Noviembre 2016, 04:32 AM
Citar
No es la solución pero me ayuda a monitorear  la memoria disponible...

Por eso mismo dije una "posible" solucion,otra "posible" solucion seria ir a panel de control/programas/java/configuracion,y alli establecer el espacio de memoria para archivos temporales.

saludos!