将逗号分隔的每行文件拆分为数组

时间:2015-07-01 08:43:57

标签: java arrays split line

目标:我正在尝试将.txt文件处理为String[]。必须每行读取文件,拼接“,”并存储在数组中。每个元素(每行6个元素)必须在数组中拥有它自己的索引,并且必须可以单独访问。

档案(部分):

210,20140101,    1,   60,   67,   -1
210,20140101,    2,   60,   65,    0
210,20140101,    3,   60,   58,    0
210,20140101,    4,   60,   56,    0
210,20140101,    5,   60,   49,    0
210,20140101,    6,   60,   53,    0
210,20140101,    7,   60,   55,    0
210,20140101,    8,   70,   59,    0
到目前为止

代码:

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    for (String line; (line = br.readLine()) != null;) {
        counter++;
        if (counter > 51) {
            line = br.readLine();
            line = line.trim();
            list = Arrays.asList(line.split("\\s*,\\s*"));
        }
    }
}

for (String x : list) {
    System.out.println(x);
}

到目前为止的输出:

  

391
  20141231个
  24个
  20个
  1
  0

这正是我需要的,但对于每一行(存储在String数组中)。使用上面的代码只将文件的最后一行存储在数组中。

我已经尝试过建议herehere。 有任何建议或提示吗?

5 个答案:

答案 0 :(得分:4)

list = Arrays.asList(line.split("\\s*,\\s*"));

此行只是替换现有元素,因此您需要追加元素,永远不要=将元素添加到list变量。

这可能会有所帮助:

list.addAll(Arrays.asList(line.split("\\s*,\\s*")));

答案 1 :(得分:2)

你应该尝试使用它。

    private BufferedReader innerReader;
public List<String> loadFrom(Reader reader)
        throws IOException {
    if(reader == null)
    {
        throw new IllegalArgumentException("Reader not found");
    }
        this.innerReader = new BufferedReader(reader);
    List<String> result = new ArrayList<String>();
    String line;
    try
    {
    while((line = innerReader.readLine()) != null)
    {
        if (line == null || line.trim().isEmpty())
            throw new IllegalArgumentException(
                    "line null");

        StringTokenizer tokenizer = new StringTokenizer(line, ",");
        if (tokenizer.countTokens() < 6)
            throw new IllegalArgumentException(
                    "Token number (<= 6)");
        String n1 = tokenizer.nextToken(",").trim();
        String n2 = tokenizer.nextToken(",").trim();
        String n3 = tokenizer.nextToken(",").trim();
        String n4 = tokenizer.nextToken(",").trim();
        String n5 = tokenizer.nextToken(",").trim();
        String n6 = tokenizer.nextToken(",\n\r").trim();
        StringBuilder sb = new StringBuilder();
        sb.append(n1 + "," + n2 + "," + n3 + "," + n4 + "," + n5 + "," + n6);
        result.add(sb.toString());
    }
    } catch (NoSuchElementException e) {
        throw new  IllegalArgumentException(e);
    }
    return result;
}

答案 2 :(得分:1)

这应该有效:

$('#links a').click(function(){                                        // when I click an 'a' element within element with ID 'links'
    $('#form').find('input[type="text"]').val($(this).data('name'));   // for the element with id 'form', find all inputs of type 'text', and set the value to the 'data-name' attribute of the clicked element
    $('#form').find('input[type="hidden"]').val($(this).data('url'));  // for the element with id 'form', find all inputs of type 'hidden', and set the value to the 'data-url' attribute of the clicked element
});

答案 3 :(得分:1)

如果您使用的是Java7,则可以使用新的Files API更轻松地读取文件:

public List<List<String>> readValuesJava7() {
  Path path = Paths.get(URI.create("/tmp/coco.txt"));
  List<String> rawLines = new ArrayList<>();
  try {
    rawLines = Files.readAllLines(path);
  } catch (IOException e) {
    e.printStackTrace();
  }
  List<List<String>> lines = new ArrayList<>();
  for (String rawLine : rawLines) {
    List<String> line = new ArrayList<>();
    for (String col : rawLine.split(","))
      line.add(col.trim());
    lines.add(line);
  }
  return lines;
}

如果您使用的是Java8,则可以将其与新的Streams API结合使用,如下所示:

public List<List<String>> readValuesJava8() {
  Path path = Paths.get(URI.create("/tmp/coco.txt"));
  Stream<String> rawLines = Stream.empty();
  try {
    rawLines = Files.lines(path);
  } catch (IOException e) {
    e.printStackTrace();
  }
  return rawLines
      .map(line -> line.split(","))
      .map(cols -> Stream.of(cols).map(String::trim).collect(Collectors.toList()))
      .collect(Collectors.toList());
}

答案 4 :(得分:0)

您可以使用String的二维数组来表示您尝试阅读的表格。我使用ArrayList来读取文件,因为在到达文件末尾之前,您不知道有多少行。我将ArrayList转换为代码示例末尾的数组。

List<String[]> resultList = new ArrayList<String[]>();
int counter = 0;
try (BufferedReader br = new BufferedReader(new FileReader(path))) {

    for (String line; (line = br.readLine()) != null;) {
        counter++;

        if (counter > 51) {                           // ignore the first 51 lines
            line = br.readLine();
            line = line.trim();
            resultList.add(line.split("\\s*,\\s*"));
        }
    }
}

String[][] resultArray = new String[counter][6];      // convert ArrayList of String[]
resultArray = resultList.toArray(resultArray);        // to an array

<强>输出:

System.out.println(resultArray[0][4]); // prints 67
System.out.println(resultArray[4][1]); // prints 20140101
System.out.println(resultArray[6][2]); // prints 7