简体   繁体   English

在JAVA中将数据从文本文件传输到MySQL表时出现OutOfMemory错误

[英]OutOfMemory Error when transferring data from text file to MySQL table in JAVA

I have a text file containing some data. 我有一个包含一些数据的文本文件。 When I tried to put the data in MySQL I get this error " java.lang.OutOfMemoryError: Java heap space ". 当我尝试将数据放入MySQL时,出现此错误“ java.lang.OutOfMemoryError: Java heap space ”。

My code: 我的代码:

        try {
        // create a buffer reader
        java.io.BufferedReader br = new BufferedReader(new FileReader(f));
        // define line
        String line = null;
        // connect to the database
        connect = (Connection) DbConnection.establishConnection();
        while ((line = br.readLine()) != null) {
            // create preparedStatement
            preparedStatement = (PreparedStatement) connect.prepareStatement("insert into  IdentifiedExpertList values (?,?)");

            String[] rowData = line.split("\\s+", 2);
            String firstColumnData = rowData[0];
            String secondColumnData = null;
            if (rowData[1].trim().isEmpty()) {
                secondColumnData = null;
            } else {
                secondColumnData = rowData[1];
            }

            preparedStatement.setString(1, firstColumnData.trim());
            preparedStatement.setString(2, secondColumnData);
            preparedStatement.executeUpdate(); 

        }
        br.close();
        }
java.lang.OutOfMemoryError: Java heap space

indicates that your allotted memory for JVM is not enough to keep up with the memory required to load the file into memory. 表示您为JVM分配的内存不足以跟上将文件加载到内存所需的内存。

You may use -Xms and -Xmx flags to allocate memory for JVM. 您可以使用-Xms-Xmx标志为JVM分配内存。 If the memory being used is very less, increase it by using those flags and see. 如果正在使用的内存非常少,请使用这些标志来增加内存并查看。

If still you are having memory issues, then another possible solution would be read chunks of the file and upload to DB instead of reading whole file at once. 如果仍然遇到内存问题,那么另一种可能的解决方案是读取文件的块并将其上传到DB,而不是一次读取整个文件。

If none of them works, that means there may be memory leak in your code. 如果它们都不起作用,则意味着代码中可能存在内存泄漏。 You need to fix it. 您需要修复它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM