简体   繁体   English

读取txt文件并制作2d char数组

[英]Reading txt file and making 2d char array

I have a txt file with the following: 我有以下内容的txt文件:

%%%%%%%
%Q%&%%%
%%%&&&%
%&%&%%%
%&%&%%%
%&%&&7%
%&%%%&%
%&&&%&%
%%%&&&%

This is just an example -- the text file could be any 2d array (varying width and height and characters). 这只是一个示例-文本文件可以是任何2d数组(宽度和高度以及字符)。

I want to read it in and make a 2d char array in java. 我想读入它并在Java中制作一个2d char数组。

I am trying to use a scanner method that reads the lines as a string and then converts to a charArray: 我正在尝试使用一种扫描程序方法,该方法将这些行读取为字符串,然后转换为charArray:

String theString = "";
        File fd = new File("input.txt");
        Scanner sc = new Scanner(fd);;
        theString = sc.nextLine();
        try {
            sc = new Scanner(fd);
        } catch (FileNotFoundException e) {
            System.out.println("File not found! Application terminated\n" + e.toString());
            return;
        }

        while (sc.hasNextLine()) {
               theString = theString + "\n" + sc.nextLine();
        }
        sc.close();
        char[][] charArray= theString.toCharArray();

However, the debugger wants me to change to char[] instead of of char[][] 但是,调试器希望我更改为char []而不是char [] []

How can I get the desired results? 如何获得理想的结果?

The str.toCharArray() method output a char[] of the original string. str.toCharArray()方法输出原始字符串的char[] So the workaround is to add it to the char[][] line-by-line instead. 因此,解决方法是逐行将其添加到char[][]

Since you do not know how many lines exactly are there in the input.txt , you cannot pre-determine the char[][] 's size. 由于您不知道input.txt到底有多少行,因此无法预先确定char[][]的大小。 One way to do so is to add it to an ArrayList so you know the size of the result array. 一种方法是将其添加到ArrayList中,以便您知道结果数组的大小。 You can then put it back the char[][] . 然后可以将其放回char[][]

String theString = "";
        File fd = new File("input.txt");
        Scanner sc = new Scanner(fd);;
        theString = sc.nextLine();
        try {
            sc = new Scanner(fd);
        } catch (FileNotFoundException e) {
            System.out.println("File not found! Application terminated\n" + e.toString());
            return;
        }

        ArrayList<String> lst = new ArrayList<>();

        while (sc.hasNextLine()) {
               lst.add(sc.nextLine());
        }
        sc.close();

        char[][] result = new char[lst.size()][lst.get(0).length()];
        for(int i = 0; i < lst.size(); i++) {
            char[] charArray= lst.get(i).toCharArray();
            result[i] = charArray;
        }        


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

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