java 我想读取一个文本文件,拆分它,并将结果存储在一个数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5576404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:44:16  来源:igfitidea点击:

I want to read a text file, split it, and store the results in an array

java

提问by Pratik

I have a text file which has 10 fields(columns)each separated by a tab.And i have several such rows.I wish to read the text file, split it for every column, using a "tab" delimiter and then storing it in an array of 10 columns and unlimited rows.Can that be done?

我有一个文本文件,它有 10 个字段(列),每个字段(列)由一个制表符分隔。我有几个这样的行。我希望读取文本文件,将其拆分为每一列,使用“制表符”分隔符,然后将其存储在一个包含 10 列和无限行的数组。可以这样做吗?

回答by Jon Skeet

An array can't have "unlimited rows" - you have to specify the number of elements on construction. You might want to use a Listof some description instead, e.g. an ArrayList.

数组不能有“无限行” - 您必须在构造时指定元素数。您可能希望使用List某种描述的 a 代替,例如 a 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.readLinesto get a List<String>, and then process that list separately, again using Splitter.)

(这使您可以在进行时拆分行……或者,您可以使用Files.readLines获取List<String>,然后单独处理该列表,再次使用Splitter。)

回答by les2

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

回答by fftk4323

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);
    }

}
}