Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将.txt读入数组_Java_Arrays_File - Fatal编程技术网

Java 如何将.txt读入数组

Java 如何将.txt读入数组,java,arrays,file,Java,Arrays,File,我想通过Java程序读取.txt文件 假设这是文本文件input.txt abc, test, 1,2,3 abc abcd test, 1, 2, 3 每行代表一行,每一个逗号分隔的值代表一列 目前我的代码是: BufferedReader br = new BufferedReader(new FileReader("input.txt")); int num = readLines(); //this function just returns the number of l

我想通过Java程序读取.txt文件

假设这是文本文件
input.txt

abc, test, 1,2,3
abc
abcd 
test, 1, 2, 3
每行代表一行,每一个逗号分隔的值代表一列

目前我的代码是:

BufferedReader br = new BufferedReader(new FileReader("input.txt"));
    int num = readLines();  //this function just returns the number of lines
    for (int i = 0; i < num; i++){
        textData[i] = br.readLine();
    }
br.close();

如何查找每行中的元素数?

创建数组列表的数组列表:

BufferedReader br = new BufferedReader(new FileReader("input.txt"));
int lineCount = readLines();

ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>(lineCount);
for (int i = 0; i < lineCount; i++) {
    ArrayList<String> row = new ArrayList<String>();
    String line = br.readLine();
    for(String s: line.split(",")) {
        row.add(s);
    }
    rows.add(row);
}
br.close();
BufferedReader br=newbufferedreader(newfilereader(“input.txt”);
int lineCount=readLines();
ArrayList行=新的ArrayList(行数);
对于(int i=0;i
您需要集合而不是数组,因为行的长度不同您的问题不清楚。代码的输出与所需的输出有何不同?将这些行读入ArrayList(正如@getlost所指出的,您的数据是可变长度的,因此数据结构应该满足这一要求),然后在需要访问每一行时,使用数组列表的.get()方法以字符串形式访问每一行,并使用.split()直接。我得到“表达式的类型必须是数组类型,但它解析为ArrayList。我认为这是因为我对类型为
ArrayList
的对象使用了
[]
运算符。我的Java有点生锈了!请参阅我的编辑。
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
int lineCount = readLines();

ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>(lineCount);
for (int i = 0; i < lineCount; i++) {
    ArrayList<String> row = new ArrayList<String>();
    String line = br.readLine();
    for(String s: line.split(",")) {
        row.add(s);
    }
    rows.add(row);
}
br.close();