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

在Java中将文本文件转换为2d数组,java,csv,multidimensional-array,2d,Java,Csv,Multidimensional Array,2d,我正在为课堂做作业,我必须打开一个文本文件,并将该文件转换成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-12Citywid

我正在为课堂做作业,我必须打开一个文本文件,并将该文件转换成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");
我的文本文件有98行15列。 文件如下:


我希望有人能帮忙。非常感谢您的先进

您可以这样做
用逗号拆分每一行,并将部分添加到列表中:

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));
}
publicstaticvoidmain(字符串[]args)引发IOException{
//URL source=Program.class.getResource(“EnglishResults06-12Citywide.csv”);//嵌入式资源
URL source=新文件(“src/EnglishResults06-12Citywide.csv”).toPath().tori().tour();//本地文件
Scanner in=new Scanner(source.openStream());
如果(!in.hasNextLine()){//oops,则文件为空
System.err.println(“缺少标题!”);
系统出口(1);
}
字符串headLine=in.nextLine();
String[]fieldNames=headLine.split(,“”;//标题类似于一条规则行,它包含字段的名称
List data=new ArrayList();//元素的支持列表(=growtable数组)
while(在.hasNextLine()中){
String line=in.nextLine();
String[]frags=line.split(,“”;//按逗号分割行,因为它是CSV
数据。添加(frags);
}
in.close();//关闭流
String[][]dataArray=data.toArray(新字符串[data.size()][]);//将数据从列表复制到数组
//打印结果
System.out.println(“字段名:”+Arrays.toString(字段名));
System.out.println(“数据数组:“+Arrays.deepToString(dataArray));
}

由于您知道列和行的数量,因此可以明确定义二维数组的长度,例如:

String[][] myArr = new String[98][];
因为您知道列的数量,所以可以在while循环之外创建一个计数器,并将其递增到while循环中。然后,可以在每个逗号处拆分该行,并将其指定给二维数组:

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));
然后可以打印二维阵列:

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

希望这对您有所帮助。

如果您对如何将其转换为数组不太明确,可以尝试使用“csv\u ml”。GitHub页面:

代码如下所示:

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

希望这有帮助。

String.split
是您的朋友,请使用它。您所指的文件格式称为CSV(逗号分隔值),考虑将其添加为标签。谢谢您的响应!!我到底在哪里使用String.split?@MichaelLaffargue注意,split的参数是一个
RegEx
模式,所以按。将被任何字符分割,如果您不确定,您可以使用
Pattern.quote(…)
在行上转义参数,使用带正则表达式的分割,您将收到一个数组=>示例:“要分割的我的行”。分割(\\s”)-->[“我的”、“行”、“到”、“分割”]。您的评论没有错,我只是想我应该提到,当按特殊字符分割时,这可能会失败……对于练习,这种显式表示法是可以的。-在这种情况下,我建议使用
For
-循环,而不是无用的
,而
-循环,它计算行数。