我有一个 txt 文件,其中包含以下内容:
%%%%%%%
%Q%&%%%
%%%&&&%
%&%&%%%
%&%&%%%
%&%&&7%
%&%%%&%
%&&&%&%
%%%&&&%
这只是一个示例 - 文本文件可以是任何二维数组(不同的宽度、高度和字符)。
我想读入它并在java中创建一个二维字符数组。
我正在尝试使用扫描仪方法将行读取为字符串,然后转换为 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();
但是,调试器希望我更改为 char[] 而不是 char[][]
怎样才能得到想要的结果?
最佳答案
str.toCharArray()
方法输出原始字符串的 char[]
。因此,解决方法是将其逐行添加到 char[][]
中。
由于您不知道 input.txt
中到底有多少行,因此您无法预先确定 char[][]
的大小。一种方法是将其添加到 ArrayList 中,以便您知道结果数组的大小。然后您可以将其放回 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;
}
关于java - 读取txt文件并制作二维字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56764610/