【问题标题】:How do I read a file in Java char by char into an integer array?java - 如何将Java char中的文件逐字符读取到整数数组中?
【发布时间】:2016-08-31 02:00:29
【问题描述】:

我有一个文件,里面全是数字,没有空格。 我正在尝试将 Java 中的这个文件一个字符一个字符地读入一个整数数组。 我尝试将文件作为字符串读取,然后逐个字符地将其逐个遍历到数组中,但我认为文件超出了字符串大小限制。

【问题讨论】:

  • 如果超过最大String大小,也会超过最大int数组大小Integer.MAX_VALUE
  • 请更具体。所以你的文件包含“1234567890 ....” - 现在你的整数数组应该是什么 [1, 2, 3, 4, ... ] 还是什么?
  • 你的文件长度是多少字节?
  • 发布一些包含您获得的结果和预期结果的代码,否则您将关闭此问题,因为这听起来像是“请做我的功课”问题。

标签: java


【解决方案1】:

正如@Scary Wombat 所建议的,字符串的最大大小和数组的最大大小都是Integer.MAX_VALUE。我们可以参考String max sizeArray max sizeList max size。请注意,具体的最大大小应为Integer.MAX_VALUE - 1 或 -2 或 -5 与本主题无关。为了保险起见,我们可以使用Integer.MAX_VALUE - 6。

我想你的数字很大,文件中的字符数可能超过Integer.MAX_VALUE的最大值,根据

我尝试将文件作为字符串读取,然后按 char 单步执行 char 到一个数组中,但我认为文件超出了字符串大小 限制。

为了处理最大值,我建议你创建另一个List 来保存整数。它的核心概念类似于dynamic array,但有一些区别。对于dynamic array,您正在申请另一个内存空间并将当前元素复制到该空间中。可以参考下面的代码:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;

public class ReadFile {
    public static void main(String args[]){
        try{        
            File file = new File("number.txt");
            FileReader fileReader = new FileReader(file);
            BufferedReader reader = new BufferedReader(fileReader);
            ArrayList<ArrayList<Integer>> listContainer = new ArrayList<ArrayList<Integer>>();
            ArrayList<Integer> list = new ArrayList<Integer>();
            int item;
            while((item = reader.read()) != -1){
                /*
                 * I assume you want to get the integer value of the char but not its ascii value
                 */
                list.add(item - 48);
                /*
                 * Reach the maximum of ArrayList and we should create a new ArrayList instance to hold the integer
                 */
                if(list.size() == Integer.MAX_VALUE - 6){
                    listContainer.add(list);
                    list = new ArrayList<Integer>();
                }
            }
            reader.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-08
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 2012-11-19
    • 1970-01-01
    • 2013-03-01
    相关资源
    最近更新 更多