在Java中将文本文件转换为2d数组

时间:2015-03-25 10:08:25

标签: java csv multidimensional-array 2d

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

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

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

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

3 个答案:

答案 0 :(得分:0)

您可以通过逗号将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));
}

答案 1 :(得分:0)

如您所知,列数和行数,您可以明确定义2D数组的长度,例如:

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

然后您可以打印2D数组:

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

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

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

希望这有帮助。

答案 2 :(得分:0)

如果您没有具体说明将其转换为数组,您可以尝试&#34; csv_ml&#34; 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"));

希望这有帮助。