简体   繁体   English

如何将文本文件转换为2D字符数组?

[英]How do you convert a text file into a 2D character array?

I am trying to convert a text file into a 2 dimensional character array. 我正在尝试将文本文件转换为二维字符数组。 I am part of the way there but the last line of my array is not fully correct. 我是那里的一部分,但数组的最后一行并不完全正确。 Here's my code: 这是我的代码:

protected void readMap(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    char[] chars;
    int lines=0;
    while (br.readLine() != null) {
        lines++;
    }
    File file = new File(fileName);
    try (FileReader reader = new FileReader(file)) {
        chars = new char[(int) file.length()];
        reader.read(chars);
        reader.close();
    } catch (IOException e) {
    }

    int columns = ((int) file.length())/lines;     

    map = new char[lines][columns];
    for(int i=0; i<lines;i++){
        for(int j=0;j<columns;j++){
           map[i][j] = chars[j%columns+i*columns];
        }
    }

    for(int ro=0; ro<map.length; ro++){
                for(int colum=0; colum<(map[0].length); colum++){
                    System.out.print(map[ro][colum]);
                }
            }
    return null;
    }

Here's the output: 这是输出:

##########################
#........................#
#.....###........###.....#
#......G..........G......#
#........................#
#...........E............#
#......G.........G.......#
#........G.....G.........#
#..........###...........#
#........................# 
#################
                 ^missing #'s here

I'm very confused on why this is occuring. 我很困惑为什么会这样。 I've tried changing how I print the array but i'm pretty sure its how its to do with how i've converted the 1d 'chars' array to the 2d 'map' array. 我试图改变我打印数组的方式,但是我很确定它与我将1d'chars'数组转换为2d'map'数组的方式有关。 I'm really lost so any help would be much appreciated! 我真的迷路了,因此不胜感激! Thank you. 谢谢。

I've just executed the code and the map prints as expected. 我刚刚执行了代码,地图按预期打印。 The issue may be down to the file itself as that is the uncommon factor. 问题可能归结于文件本身,因为这是不常见的因素。

edit: The results you have observed is because you may have a new line character, or other special character, at the end of or somewhere in the file. 编辑:您观察到的结果是因为您可能在文件的结尾或某处有换行符或其他特殊字符。 Removing this you should see the consistent map you want. 删除它,您应该会看到所需的一致映射。

Alternative 另类

protected static void readMap(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    String line = "";
    List<String> lines = new ArrayList<>();
    while ((line = br.readLine()) != null) {
        lines.add(line);
    }

    char[][] chars = new char[lines.size()][];
    for (int col = 0; col < lines.size(); col++) {
        for (int row = 0; row < lines.get(col).length(); row++) {
            chars[col] = lines.get(col).toCharArray();
        }
    }

    for (int col = 0; col < chars.length; col++) {
        for (int row = 0; row < chars[col].length; row++) {
            System.out.print(chars[col][row]);
        }
        System.out.println();
    }
}//My rows and cols may be back to front

Few other notes: 其他注意事项:

  1. You shouldn't be returning a value from a void method, even null (You'll want to return null if the return type is Void). 您不应该从void方法返回值,甚至不返回null(如果返回类型为Void,则希望返回null)。
  2. Your compiler may complain if you don't initialize chars initially, as mine did. 如果您最初不像我一样初始化char,则编译器可能会抱怨。 char[] chars = null; would do it in this scenario. 在这种情况下会做到这一点。

I'm guessing your file looks something like this 我猜你的文件看起来像这样

##########################
#........................#
#.....###........###.....#
#......G..........G......#
#........................#
#...........E............#
#......G.........G.......#
#........G.....G.........#
#..........###...........#
#........................#
##########################

If you print the file length, you will see that the file length is 296 如果您打印文件长度,您将看到文件长度为296

As Your code row = 11 and columns = 26 由于您的代码row = 11 columns = 26

When you are copying to map you are copying up to 11 * 26 = 286 复制到地图时,最多复制11 * 26 = 286

Try the UPDATED code below 试试下面的更新代码

public void readMap(String fileName) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    int lines = 0, columns = 0;
    String str;
    List<String> lineList = new ArrayList<>();
    while ((str = br.readLine()) != null && str.length() != 0) {
        lines++;
        columns = Math.max(columns, str.length()); // as it's not fixed
        lineList.add(str);
    }
    System.out.println("Row : " + lines);
    System.out.println("Columns : " + columns);

    char[][] map = new char[lines][columns];
    for (int i = 0; i < lines; i++) {
        String currentLine = lineList.get(i);
        int idx = 0;
        for (int j = 0; j < currentLine.length(); j++) {
            map[i][j] = currentLine.charAt(idx++);
        }
    }
    for (int r = 0; r < map.length; r++) {
        for (int c = 0; c < (map[0].length); c++) {
            System.out.print(map[r][c]);
        }
        System.out.println();
    }
}

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

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