【问题标题】:Turning a text file into a 2d array in Java在Java中将文本文件转换为二维数组
【发布时间】:2015-05-28 22:46:28
【问题描述】:

我正在为班级做作业,我必须打开一个文本文件并将该文件转换为二维数组,以便以后可以根据用户的请求访问它。

到目前为止,我的代码是这样的:

public static void main(String[] args) throws  FileNotFoundException {

    //create a scanner with the file as input
    Scanner in = new Scanner(new File("src/EnglishResults06-12Citywide.csv"));

     //check to see if there's a line available in the file
     while(in.hasNextLine()){

         //get the next line
         String line = in.nextLine();

     }

     //close scanner
     in.close();

     //turns file into multi-dimensional array

     String[][] grades = new String[98][15];               

     for (int i=0; i<results.length; i++) { //loop through each row
        for (int j=0; j<results[i].length; j++) { //loop through all columns within the current row

            results[i][j] = request //not sure how to assign the imported csv to the variable request
        }
     }

     System.out.printf("Grade", "Year" , "Demographic" , "Number Tested" , "Mean Scale Score" , "Num Level 1" , "Pct Level 1" , "Num Level 2" , "Pct Level 2" , "Num Level 3" , "Pct Level 3" , "Num Level 4" , "Pct Level 4" , "Num Level 3 and 4" , "Pct Level 3 and 4");

我已经导入了以下内容:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

我的文本文件有 98 行和 15 列。 这是文件:http://txt.do/xjar

我希望有人可以提供帮助。非常感谢你!!!

【问题讨论】:

  • String.split 是你的朋友,使用它。您所指的文件格式称为 CSV(逗号分隔值),请考虑将其添加为标签。
  • 感谢您的回复!!我究竟会在哪里使用 String.split?
  • @MichaelLaffargue 注意,split 的参数是RegEx 模式,所以用 分割。 将被 任何字符 分割,如果你不确定,您可以使用Pattern.quote(...) 转义参数
  • 在线上,使用正则表达式拆分,您将收到一个数组 => 示例:“我要拆分的行”.split("\\s") --> ["my ","line","to","split"]。 docs.oracle.com/javase/tutorial/essential/regex/…
  • 你的评论没有错,我只是想我应该提一下,当用特殊字符分割时这可能会失败......

标签: java csv multidimensional-array 2d


【解决方案1】:

您可以对split 每行用逗号执行类似操作,然后将部分添加到列表中:

public static void main(String[] args) throws IOException {
    //URL source = Program.class.getResource("EnglishResults06-12Citywide.csv"); //embedded resource
    URL source = new File("src/EnglishResults06-12Citywide.csv").toPath().toUri().toURL(); //local file
    Scanner in = new Scanner(source.openStream());
    if (!in.hasNextLine()) { //oops, the file is empty
        System.err.println("Missing headline!");
        System.exit(1);
    }
    String headLine = in.nextLine();
    String[] fieldNames = headLine.split(","); //the headline is like a regular line, it holds the names of the fields
    List<String[]> data = new ArrayList<>(); //backing list (=growable array) for the elements 
    while (in.hasNextLine()) {
        String line = in.nextLine();
        String[] frags = line.split(","); //split line by comma, because it's CSV
        data.add(frags);
    }
    in.close(); //close the stream

    String[][] dataArray = data.toArray(new String[data.size()][]); //copy data from the list to an array

    //print out results
    System.out.println("Field names: " + Arrays.toString(fieldNames));
    System.out.println("Data array: " + Arrays.deepToString(dataArray));
}

【讨论】:

    【解决方案2】:

    既然知道列数和行数,就可以显式定义二维数组的长度如:

    String[][] myArr = new String[98][];
    

    因为您知道列数,所以您可以在 while 循环之外创建一个计数器,然后将其递增到 while 循环中。然后,您可以在每个逗号处拆分行,并将其分配给 2D 数组:

    int i = 0;
    //remember to skip the headers
    in.nextLine();
        while(in.hasNextLine()){
             //get the next line
             String line = in.nextLine();
             myArr[i] = line.split(",");
             i++;
         }
    

    然后您可以打印二维数组:

    System.out.println(Arrays.deepToString(myArr));
    

    或者您可以要求第 i 个索引中的任何列,例如:

    System.out.println(myArr[0][0]);
    

    希望这会有所帮助。

    【讨论】:

    • 对于练习,这个明确的符号是可以的。 - 在这种情况下,我建议使用 for-loop 代替无用的 while-loop 来计算行数。
    【解决方案3】:

    如果您不具体将其转换为数组,您可以尝试“csv_ml”http://siara.cc/csv_ml/csvdoc.pdf。 GitHub页面:https://github.com/siara-cc/csv_ml

    代码是这样的:

    import java.io.FileReader;
    import java.io.Reader;
    
    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;
    
    import cc.siara.csv_ml.MultiLevelCSVParser;
    
    public class Convert {
       public static void main(String args[]) throws Exception {
         Reader r = new FileReader("input.csv");
         MultiLevelCSVParser parser = new MultiLevelCSVParser();
         JSONObject jso = (JSONObject) parser.parse("jso", r, false);
         String ex_str = parser.ex.get_all_exceptions();
         if (ex_str.equals("")) {
            JSONArray rows = (JSONArray)jso.get("n1");
            System.out.println(((JSONObject)rows.get(0)).get("c1"));
         } else
             System.out.println(ex_str);
       }
    }
    

    如果您需要使用标题进行引用,则需要在 CSV 文件的开头添加以下行。

    csv_ml,1.0,UTF-8,root,no_node_name,inline
    

    那么该列可以称为:

    System.out.println(((JSONObject)rows.get(0)).get("Grade"));
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-12
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 2015-02-04
      • 1970-01-01
      • 2012-07-11
      • 2020-10-04
      相关资源
      最近更新 更多