如何从文本文件中获取字符并将其放入2D数组中?
- 阅读文本文件一行一行
- 分割字符串由
-
这样你才会有字符数组加上它在你的二维字符数组。
最简单的方法是使用String的toCharArray()方法。
所以,如果你正在使用一个BufferedReader
ArrayList<String> list = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader("file"));
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
// finally convert the arraylist to a char[]
char[] firstDimension = new char[list.size()];
for (int i = 0; i < list.length; i++) {
firstDimension[i] = list.get(i).toCharArray();
}
如果即时使用扫描仪? – 2010-12-19 18:59:51
bufferedreader可能更适合这个,但另外使用扫描仪逐行阅读 – Codemwnci 2010-12-19 19:30:34
的char [] firsDimension不是2D。尝试类似,
try {
List<String> list = new ArrayList<String>();
String thisLine = null;
BufferedReader br;
br = new BufferedReader(new FileReader("/path/to/file/yourfile.txt"));
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
char[][] firstDimension = new char[list.size()][];
for (int i = 0; i < list.size(); i++) {
firstDimension[i] = list.get(i).toCharArray();
}
//print values
for (int i=0;i<firstDimension.length;i++) {
for (int j=0;j<firstDimension[i].length;j++) {
System.out.println(firstDimension[i][j]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
随着扫描器类
try {
Scanner scanner = new Scanner(new File(
"/home/sinan/Desktop/yourfile.txt"));
scanner.useDelimiter(System.getProperty("line.separator"));
ArrayList<String> list = new ArrayList<String>();
while (scanner.hasNext()) {
list.add(scanner.next());
}
scanner.close();
// finally convert the arraylist to a char[][]
char[][] firstDimension = new char[list.size()][];
for (int i = 0; i < list.size(); i++) {
firstDimension[i] = list.get(i).toCharArray();
}
for (int i = 0; i < firstDimension.length; i++) {
for (int j = 0; j < firstDimension[i].length; j++) {
System.out.println(firstDimension[i][j]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
如果我使用扫描仪,它会怎么样? – 2010-12-19 19:08:49
但如果我想打印双数组我只想要我写的没有其余的? – 2010-12-19 19:47:25
是否示例示出了文件或所需的2D输出阵列的输入线? – 2010-12-19 18:35:08
它只是简单,你需要按照我的回答中的2个步骤 – 2010-12-19 20:37:52