Java 如何将.txt读入数组
我想通过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
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();