首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >OutOfMemoryError:尝试创建ArrayList时的Java堆空间

OutOfMemoryError:尝试创建ArrayList时的Java堆空间
EN

Stack Overflow用户
提问于 2020-03-02 18:58:48
回答 1查看 48关注 0票数 0

我正在试着写一个程序,它可以将G代码的所有G1行转换为MOVX (x-coordinate of G1 command)

例如:G1 X0.1851应该成为MOVX(0.1851)

此时,程序只是附加已读取的文本文件,并在同一文本文件中的旧代码下面打印新代码。

问题是,当我尝试在G-Code中创建X后面的数字的数组列表时,堆空间中的内存溢出了。

我在G-Code的一行的每次迭代后添加了一条clear()语句,试图防止数组列表变得越来越大,但它总是溢出。

下面是我的代码:

代码语言:javascript
复制
package textfiles;
import java.io.IOException;
import java.util.ArrayList;


public class FileData {

    public static void main(String[] args) throws IOException {

        String file_name = "C:/blabla";

        try {
            ReadFile file = new ReadFile(file_name);
            WriteFile data = new WriteFile(file_name, true);
            String[] aryLines = file.OpenFile();

            int i;
            int j;
            int y;

            for (i=0; i < aryLines.length; i++ ) { //goes through whole text file
                System.out.println( aryLines[ i ]);

                if (i == 0) {
                    data.writeToFile("");
                    System.lineSeparator();
                }

                char[] ch = aryLines[ i ].toCharArray();
                ArrayList<Character> num = new ArrayList<Character>();
                String xCo = null;


                boolean counterX = false;

                if ((ch[0]) == 'G' && ch[1] == '1') {

                    for (j = 0; j < ch.length; j++) { //goes through each line of text file

                        for (y = 0; counterX == true; y++) {
                            num.add(ch[j]);
                        }

                        if (ch[j] == 'X') {
                            counterX = true;
                        }

                        else if (ch[j] == ' ') {
                            counterX = false;
                        }
                    }
                    xCo = num.toString();
                    data.writeToFile("MOVX (" + xCo + ")");
                }
                num.clear();
            }
        }
        catch (IOException e) {
            System.out.println( e.getMessage() );
        }

        System.out.println("Text File Written To");

    }
}
EN

回答 1

Stack Overflow用户

发布于 2020-03-02 23:41:07

我建议避免将数据读取到内存中,而使用流。然后,转换行的函数可能如下所示:

代码语言:javascript
复制
    public void convertFile(String fileName, String tmpFileName) throws IOException {
        try (FileWriter writer = new FileWriter(tmpFileName, true)){
            Pattern pG1_X = Pattern.compile("^G1 X");
            Files.newBufferedReader(Paths.get(fileName)).lines().forEach(line -> {
                try {
                    double x = Double.parseDouble(pG1_X.split(line)[1]); // get coordinate
                    String newLine = String.format("MOVX(%f)\n",x);      // attempt to replace coordinate format
                    writer.write(newLine);
                } catch (Exception e) {
                    LOGGER.log(Level.WARNING, String.format("error wile converting line %s", line), e);
                }
            });
        }
    }

演示其工作原理的测试用例:

代码语言:javascript
复制
package com.github.vtitov.test;

import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Random;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import java.nio.file.StandardCopyOption;

@RunWith(Theories.class)
public class ReadWriteTest {
    final static Logger LOGGER = Logger.getLogger(ReadWriteTest.class.getName());

    public void convertFile(String fileName, String tmpFileName) throws IOException {
        try (FileWriter writer = new FileWriter(tmpFileName, true)){
            Pattern pG1_X = Pattern.compile("^G1 X");
            Files.newBufferedReader(Paths.get(fileName)).lines().forEach(line -> {
                try {
                    double x = Double.parseDouble(pG1_X.split(line)[1]); // get coordinate
                    String newLine = String.format("MOVX(%f)\n",x);      // attempt to replace coordinate format
                    writer.write(newLine);
                } catch (Exception e) {
                    LOGGER.log(Level.WARNING, String.format("error wile converting line %s", line), e);
                }
            });
        }
    }


    @DataPoints static public Long[] fileSizes() {return new Long[]{100L,10_000L,1_000_000L}; }
    @Theory
    public void readWriteTest(Long fileSize) throws Exception {
        TemporaryFolder folder = TemporaryFolder.builder().parentFolder(new File("target")).build();
        folder.create();
        File file = folder.newFile(UUID.randomUUID() + ".txt");
        File tmpFile = folder.newFile(file.getName() + ".tmp");
        createFile(fileSize, file);
        String filePath = file.getPath();
        LOGGER.info(String.format("created file %s of %d lines", filePath, fileSize));
        String tmpFilePath = filePath + ".tmp";
        convertFile(filePath, tmpFilePath);
        LOGGER.info(String.format("file %s converted to %s", filePath, tmpFilePath));
        //assert false;
        Files.move(new File(tmpFilePath).toPath(), new File(filePath).toPath(),
                StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
        LOGGER.info(String.format("file %s moved to %s", tmpFilePath, filePath));
        folder.delete();
    }

    private void createFile(long fileSize, File file) throws Exception {
        try (FileWriter writer = new FileWriter(file,true)) {
            Random rnd = new Random();
            rnd.doubles(fileSize).forEach(l -> {
                try { writer.write(String.format("G1 X%f\n", l)); } catch (IOException ignored) {}
            });
        }
    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60487456

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档