【问题标题】:Fast way read a large array from console, with memory constraint从控制台读取大数组的快速方法,具有内存限制
【发布时间】:2019-06-06 08:39:00
【问题描述】:

我有这个测试数据:

public class InputTest {

    @Before
    public void setUp() throws Exception {
        ByteArrayInputStream in = new ByteArrayInputStream("90 22 11 4 5\n".getBytes());
        System.setIn(in);
    }

我需要从 InputStream 中读取每个数字作为整数。我创建了这个测试:

@Test
public void read() throws IOException {
    int c;
    while ((c = System.in.read()) != '\n') {
        int i = readInt(c);
        if (i != -1)
            System.out.print(i);
    }
}

private static int readInt(int c) {
    int ret = 0;
    if (c >= '0' && c <= '9') {
        return ret * 10 + c - '0';
    }
    return -1;
}

我有这个输出:90221145 - 我将每个 int 打印到控制台。但我需要单独的数字,如源字符串 - 90 22 11 4 5

我可以改成:

@Test
public void read() throws IOException {
    int c;
    StringBuilder b = new StringBuilder();
    while ((c = System.in.read()) != '\n') {
        int i = readInt(c);
        if (i != -1) {
            b.append(i);
        }else {
            b.append(" ");
        }
    }
    System.out.println(b.toString());
}

private static int readInt(int c) {
    int ret = 0;
    if (c >= '0' && c <= '9') {
        return ret * 10 + c - '0';
    }
    return -1;
}

但我不想在每一步都创建 StringBuilder。我该怎么做?

P.S 我知道BufferedReader's readLine() 方法和StringTokinizer,但这不适合。我需要读取字节。我解决了存储这些数据的问题,我只需要快速阅读。

这是一个面试任务的例子,我需要读取一个有内存限制的大数组。

【问题讨论】:

    标签: java arrays algorithm byte inputstream


    【解决方案1】:

    在读取数据时将其写入 System.out 怎么样

    @Test
    public void read() throws IOException {
        int c;
        StringBuilder b = new StringBuilder();
        while ((c = System.in.read()) != '\n') {
            int i = readInt(c);
            if (i != -1) {
                System.out.print(""+i);
            }else {
                System.out.print(" ");
            }
        }
        System.out.print("\n"); // end of line
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多