Java如何将文本文档中的字符串读取到字符串数组?

文件中的字符串是这样
123456 654321
1234567 7654321
1234 4321
想要读取成
a[0][0]=123456,a[0][1]=654321
a[1][0]=1234567,a[1][1]=7654321
a[2][0]=1234,a[2][1]=4321
这个样子的

使用RandomAccessFile先读取一次计算行数,seek重置到文件头部,再读取每行,赋值给a数组。

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Test {
 //此题目关键是根据文件内容确定二维数组的行数和列数
 public static void main(String[] args) {
  RandomAccessFile reader = null;
  try {
   reader = new RandomAccessFile("test.txt", "r");
   int n = 0;//行数
   while (reader.readLine() != null) {//第一次按行读取只为了计算行数
    n++;
   }
   String[][] a = new String[n][];
   reader.seek(0);//重置到文件头部
   int j;
   String line;
   String[] strs;
   int i=0;
   while ((line = reader.readLine()) != null) {//第二次按行读取是真正的读取数据
    strs = line.split(" ");//把读取到的一行数据以空格分割成子字符串数组
    a[i]=new String[strs.length];//列数就是数组strs的大小,此句是逐行创建二维数组的列
    for (j = 0; j < strs.length; j++) {
     a[i][j] = strs[j];//逐行给二维数组的每一列赋值
    }
    i++;
   }
   for (i = 0; i < n; i++) {
    for (j = 0; j < a[i].length; j++) {
     System.out.println("a[" + i + "][" + j + "]=" + a[i][j]);
    }
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (reader != null) {
    try {
     reader.close();
     reader = null;
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}

运行结果如图

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-06-01
定义一个二维数组,然后这个文本文件按行读取,用空格split,最后二重for循环按下标索引赋值就可以了。
第2个回答  2019-06-01
1.读取一行
2.通过空格切割字符串成一个数组
3.将数组中赋值给二维数组
读取步骤就不写了,大概代码
String[][] str = new String[10][10];
String line = "";
int i = 0;
while((line = rf.readLine) != -1){
str[i] = line.split(" ");
i++;
}
第3个回答  2019-06-01
import java.util.*;
import java.io.*;

public class Exam
{
public static void main(String[] args) throws Exception
{
//将FilePath修改为你的文件的实际路径
final String FilePath="t.txt";
Scanner sc=new Scanner(new File(FilePath));
ArrayList<String[]> al=new ArrayList<String[]>();
String line;
String[][] a;

while(sc.hasNext())
{
line=sc.nextLine().trim();
if(null!=line&&!line.isEmpty())
al.add(line.split("\\s+"));
}
a=new String[al.size()][];
al.toArray(a);
//输出
for(String[] strs : a)
{
for(String str : strs)
System.out.printf("%s ",str);
System.out.println();
}
sc.close();
}
}本回答被提问者和网友采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网