[英]I want to read a text file, split it, and store the results in an array
我有一个文本文件,其中有10个字段(列),每个字段由一个选项卡分隔。我有几个这样的行。我希望读取该文本文件,使用“标签”定界符将其拆分为每一列,然后将其存储在由10列和无限制行组成的数组吗?
An array can't have "unlimited rows" - you have to specify the number of elements on construction. 数组不能有“无限行”-您必须指定构造中的元素数。 You might want to use a List
of some description instead, eg an ArrayList
. 您可能想要使用一些描述的List
,例如ArrayList
。
As for the reading and parsing, I'd suggest using Guava , particularly: 至于阅读和解析,我建议使用Guava ,特别是:
(That lets you split the lines as you go... alternatively you could use Files.readLines
to get a List<String>
, and then process that list separately, again using Splitter
.) (这使您可以在Files.readLines
拆分行...或者,可以使用Files.readLines
获得List<String>
,然后再次使用Splitter
单独处理该列表。)
BufferedReader buf = new BufferedReader(new FileReader(fileName));
String line = null;
List<String[]> rows = new ArrayList<String[]>();
while((line=buf.readLine())!=null) {
String[] row = line.split("\t");
rows.add(row);
}
System.out.println(rows.toString()); // rows is a List
// use rows.toArray(...) to convert to array if necessary
Here is a simple way to load a .txt file and store it into a array for a set amount of lines. 这是加载.txt文件并将其存储到数组中的特定数量行的简单方法。
import java.io.*;
public class TestPrograms {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String conent = new String("da");
String[] daf = new String[5];//the intiger is the number of lines +1 to
// account for the empty line.
try{
String fileName = "Filepath you have to the file";
File file2 = new File(fileName);
FileInputStream fstream = new FileInputStream(file2);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
int i = 1;
while((conent = br.readLine()) != null) {
daf[i] = conent;
i++;
}br.close();
System.out.println(daf[1]);
System.out.println(daf[2]);
System.out.println(daf[3]);
System.out.println(daf[4]);
}catch(IOException ioe){
System.out.print(ioe);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.