Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何读取.txt文件并将其结构切换为二维列表_Java_List_Arraylist - Fatal编程技术网

Java 如何读取.txt文件并将其结构切换为二维列表

Java 如何读取.txt文件并将其结构切换为二维列表,java,list,arraylist,Java,List,Arraylist,我被这些数据结构弄糊涂了,我只想构建一个2D类型的结构来使用数据 以下是txt文件: 成本为B C D E F G H I J供应 资料来源1 6 7 10 16 5 8 15 6 8 175 资料来源210417139182097200 资料来源394811201085910225 资料来源41289106154970300 资料来源5 6 9 17 7 6 13 6 7 6 0 250 资料来源6 9 10 9 13 9 8 9 3 4 9 100 资料来源7 16 18 7 14 5 6

我被这些数据结构弄糊涂了,我只想构建一个2D类型的结构来使用数据

以下是txt文件:

成本为B C D E F G H I J供应
资料来源1 6 7 10 16 5 8 15 6 8 175
资料来源210417139182097200
资料来源394811201085910225
资料来源41289106154970300
资料来源5 6 9 17 7 6 13 6 7 6 0 250
资料来源6 9 10 9 13 9 8 9 3 4 9 100
资料来源7 16 18 7 14 5 6 10 5 4 5 150
资料来源8 7 5 8 3 8 5 10 8 14 300
资料来源9 8 10 9 6 4 9 17 7 5 8 100
资料来源10 5 8 4 5 7 14 6 3 13 9 200
需求150 250 110 275 175 350 300 180 90 120

以下是我目前的代码:

public static void main(String[] args) {
    Object[][] table = new Object[13][];
    Scanner sc = new Scanner(System.in);
    //sc.useDelimiter("\\Z"); 

    while(sc.hasNextLine()) {
        String sc1 = sc.nextLine();
        ArrayList<String> arrayList = 
            new ArrayList<String>(Arrays.asList(sc1.split(" ")));

        System.out.println(arrayList);      
    }

    sc.close();
}
publicstaticvoidmain(字符串[]args){
对象[][]表=新对象[13][];
扫描仪sc=新的扫描仪(System.in);
//sc.useDelimiter(“\\Z”);
while(sc.hasNextLine()){
字符串sc1=sc.nextLine();
ArrayList ArrayList=
新的ArrayList(Arrays.asList(sc1.split(“”));
System.out.println(arrayList);
}
sc.close();
}

我猜您希望将数据加载到
table=new Object[13][]如果是,这是您需要使用的代码

public static void main(String[] args) {
    Object[][] table = new Object[13][];
    Scanner sc = new Scanner(System.in);
    int i = 0;
    while (sc.hasNextLine()) {
        String sc1 = sc.nextLine();
        table[i] = sc1.split(" ");
        i++;
    }
    sc.close();
    System.out.println(Arrays.deepToString(table));
}

基本上,我只是将表中的每个索引设置为一个字符串数组,该数组包含按空格分割的字符串。

显然可以使用数组来完成这类操作,但是没有简单的方法可以知道您可能正在读取的文件中包含多少数据行,除非您知道您将要读取的特定数据文件将始终包含相同数量的数据行。许多程序员将使用ArrayList或List接口对象来保存数据,如果仍然需要类型为的数组,则集合将转换为该类型的数组

填充二维数组:

首先,您需要知道数据文件中实际包含多少有效的文件行数据。最简单的方法是进行两次读取。第一个过程统计文件中有多少有效数据行,以便正确标注数组大小,然后第二个过程填充二维数组。有简单的方法可以确定文件可能包含的行数,但没有简单的方法可以确定它们是否是有效的数据行(实际包含数据的行)

您的特定数据文件似乎包含三个特定部分:

  • 标题部分(文件的第一行)
  • 原始数据部分(文件体)
  • 需求部分(文件的最后一行)
  • 将每个部分检索到单独的数组中是有益的,因此我在下面提供的代码演示了如何实现这一点。首先,您需要建立3个类成员变量,这些变量将对整个类具有全局作用域:

    String[] headerData;  // First data Line in file is the Header Information
    Object[][] data;      // The 2D Object Array to hold raw File Data
    int[] demandData;     // Last data line in file is the Demand Information
    
    现在将以下方法复制/粘贴到类中:

    private void readDataFile(String filePath) {
        Scanner sc;
        int maxColumns = 0;
        int validLines = 0;
        int endLine;
        try {
            sc = new Scanner(new File(filePath));
            String dataLine = "";
            // First Pass: 
            while (sc.hasNextLine()) {
                String fileLine = sc.nextLine().trim();
                /* Skip Blank Lines or lines that start with 
                   a comment character (if any)... */
                if (fileLine.equals("") || fileLine.startsWith(";") || fileLine.startsWith("#")) {
                    continue;
                }
                validLines++;  //This line must be a valid data line, so increment counter.
                dataLine = fileLine;
                if (validLines == 1) {
                    // Get Header Information.
                    headerData = dataLine.split("\\s+");  // Grab the Columns Header Names
                    maxColumns = headerData.length;       // Get the number of data columns
                }
            }
            endLine = validLines;
            demandData = new int[endLine - 2];          // Initialize the demandData array
            data = new Object[endLine - 2][maxColumns]; // Initialize the data array 
            // Make sure the last line actually contains data
            if (dataLine.equals("")) {
                // No it doesn't so there is no DEMAND line.
                System.out.println("No DEMAND Data Available In File!");
                sc.close();
                return;
            }
    
            /* Fill the demandData int array with Integer data...
               The dataLine variable at this point will hold 
               the last valid file data line which happend to 
               be the Demand Line   */
            String[] dl = dataLine.split("\\s+"); // split the data line on 1 or more whitespaces.
            // Don't want the word "DEMAND" so we start from 1.
            for (int i = 1; i < dl.length; i++) {
                demandData[i-1] = Integer.parseInt(dl[i]);
            }
    
            // Second Pass (fill the data aray):
            sc = new Scanner(new File("MyDataFile.txt"));
            validLines = 0;
            while (sc.hasNextLine()) {
                String fileLine = sc.nextLine().trim();
                /* Skip Blank Lines or lines that start with 
                   a comment character (if any)... */
                if (fileLine.equals("") || fileLine.startsWith(";") || fileLine.startsWith("#")) {
                    continue;
                }
                validLines++;  //This line must be a valid data line, so increment counter.
                if (validLines == endLine) {
                    break;
                }
                if (validLines == 1) { continue; }  // Skip the header line
                dl = fileLine.split("\\s+");        // split the data line on 1 or more whitespaces.
                for (int i = 0; i < dl.length; i++) {
                    if (i == 0) {
                        data[validLines-2][i] = dl[i]; //String Object - Sources Name
                    }
                    else {
                        data[validLines-2][i] = Integer.parseInt(dl[i]); // Integer Object
                    }
                }
            }
            sc.close();  /* Close the reader.
            Make sure the number of data rows equals the number 
            of Demand values otherwise inform of mismatch. */
            if (data.length != demandData.length) {
                System.out.println("Warning: There is missing DEMAND information (data mismatch)!\n"
                                 + "There is no available Demand data for one of the Sources.");
            }
        }
        catch (FileNotFoundException ex) {
            System.err.println(ex.getMessage());
        }
    }
    
    填充二维列表界面:

    在这里,我们做一些不同的事情,你会看到它是多么容易。这一次,我们的readDataFile()方法返回一个字符串类型的2D列表接口对象,我们可以轻松地操作该对象以获取标题列名、原始数据和需求数据值

    方法如下:

     private List<List<String>> readDataFile(String filePath) {
        Scanner sc;
        List<List<String>> list = new ArrayList<>();
        try {
            sc = new Scanner(new File(filePath));
            while (sc.hasNextLine()) {
                String fileLine = sc.nextLine().trim();
                /* Skip Blank Lines or lines that start with 
                   a comment character (if any)... */
                if (fileLine.equals("") || fileLine.startsWith(";") || fileLine.startsWith("#")) {
                    continue;
                }
                /* Valid data line we want...add it to the list.
                   Here we split the data line into a String array
                   then we use the Arrays.asList() method to convert
                   it to a List then we add that List to our 2D List. 
                   All done in one line of code.  */
                list.add(Arrays.asList(fileLine.split("\\s+")));
            }
            sc.close();     // Close the reader.
        }
        catch (FileNotFoundException ex) {
            System.err.println(ex.getMessage());
        }
        return list;
    }
    
    private List readDataFile(字符串文件路径){
    扫描仪sc;
    列表=新的ArrayList();
    试一试{
    sc=新扫描仪(新文件(文件路径));
    while(sc.hasNextLine()){
    字符串fileLine=sc.nextLine().trim();
    /*跳过空行或以开头的行
    注释字符(如果有)*/
    if(fileLine.equals(“”| | fileLine.startsWith(“;”)| | fileLine.startsWith(“#”){
    继续;
    }
    /*我们需要的有效数据行…将其添加到列表中。
    这里我们将数据行拆分为一个字符串数组
    然后我们使用Arrays.asList()方法来转换
    将其添加到列表中,然后将该列表添加到2D列表中。
    所有这些都在一行代码中完成*/
    添加(Arrays.asList(fileLine.split(\\s+)));
    }
    sc.close();//关闭读卡器。
    }
    捕获(FileNotFoundException ex){
    System.err.println(例如getMessage());
    }
    退货清单;
    }
    
    要对示例数据文件使用此方法,请执行以下操作:

    // Read the file data and place it all into a 2D List
    List<List<String>> list = readDataFile("10by10.txt");
    
    // Get the Header Column Names from first ArrayList
    String[] headerData = list.get(0).toArray(new String[0]);   
    
    // The 2D Object Array to hold raw File Data
    Object[][] data = new Object[list.size() - 2][headerData.length];      
    for(int i = 1; i < list.size() - 1; i++) {
        for (int j = 0; j < list.get(i).size(); j++) {
            if (j == 0) {
                data[i - 1][j] = list.get(i).get(j);
            }
            else {
                data[i - 1][j] = Integer.parseInt(list.get(i).get(j));
            }
        }
    }
    
    // Last data line in file is the DEMAND Values
    String[] tmp = list.get(list.size() - 1).toArray(new String[0]);
    int[] demandData = new int[tmp.length - 1];
    for (int i = 1; i < tmp.length; i++) {
        demandData[i - 1] = Integer.parseInt(tmp[i]);
    }
    
    if (data != null) {
        // Header Information:
        System.out.println("Header Column Names:\n"
                + Arrays.toString(headerData) + "\n");
    
        // The Actual Data:
        System.out.println("File Data:");
        for (int i = 0; i < data.length; i++) {
            System.out.println(Arrays.toString(data[i]));
        }
    
        // The Demand Information:
        System.out.println("\nDemand Values For Each Row:\n"
                + Arrays.toString(demandData) + "\n");
    }
    
    //读取文件数据并将其全部放入2D列表中
    List List=readDataFile(“10by10.txt”);
    //从第一个ArrayList获取标题列名
    String[]headerData=list.get(0.toArray)(新字符串[0]);
    //用于保存原始文件数据的二维对象数组
    Object[][]数据=新对象[list.size()-2][headerData.length];
    对于(int i=1;i

    控制台窗口的输出将与前面显示的相同。

    这里有什么不起作用?@SamzSakerz我想建立一个2D类型的结构,如2D列表或2D ArrayList检查我的答案,看看这是否是您想要的。谢谢,这很有帮助。只是想确定一下
     private List<List<String>> readDataFile(String filePath) {
        Scanner sc;
        List<List<String>> list = new ArrayList<>();
        try {
            sc = new Scanner(new File(filePath));
            while (sc.hasNextLine()) {
                String fileLine = sc.nextLine().trim();
                /* Skip Blank Lines or lines that start with 
                   a comment character (if any)... */
                if (fileLine.equals("") || fileLine.startsWith(";") || fileLine.startsWith("#")) {
                    continue;
                }
                /* Valid data line we want...add it to the list.
                   Here we split the data line into a String array
                   then we use the Arrays.asList() method to convert
                   it to a List then we add that List to our 2D List. 
                   All done in one line of code.  */
                list.add(Arrays.asList(fileLine.split("\\s+")));
            }
            sc.close();     // Close the reader.
        }
        catch (FileNotFoundException ex) {
            System.err.println(ex.getMessage());
        }
        return list;
    }
    
    // Read the file data and place it all into a 2D List
    List<List<String>> list = readDataFile("10by10.txt");
    
    // Get the Header Column Names from first ArrayList
    String[] headerData = list.get(0).toArray(new String[0]);   
    
    // The 2D Object Array to hold raw File Data
    Object[][] data = new Object[list.size() - 2][headerData.length];      
    for(int i = 1; i < list.size() - 1; i++) {
        for (int j = 0; j < list.get(i).size(); j++) {
            if (j == 0) {
                data[i - 1][j] = list.get(i).get(j);
            }
            else {
                data[i - 1][j] = Integer.parseInt(list.get(i).get(j));
            }
        }
    }
    
    // Last data line in file is the DEMAND Values
    String[] tmp = list.get(list.size() - 1).toArray(new String[0]);
    int[] demandData = new int[tmp.length - 1];
    for (int i = 1; i < tmp.length; i++) {
        demandData[i - 1] = Integer.parseInt(tmp[i]);
    }
    
    if (data != null) {
        // Header Information:
        System.out.println("Header Column Names:\n"
                + Arrays.toString(headerData) + "\n");
    
        // The Actual Data:
        System.out.println("File Data:");
        for (int i = 0; i < data.length; i++) {
            System.out.println(Arrays.toString(data[i]));
        }
    
        // The Demand Information:
        System.out.println("\nDemand Values For Each Row:\n"
                + Arrays.toString(demandData) + "\n");
    }