Java从文件ant读取字符串并将其放入多维数组

Java从文件ant读取字符串并将其放入多维数组,java,multidimensional-array,readfile,Java,Multidimensional Array,Readfile,基本上,我有一堆信息,我需要从文件中读取并将其放入2D数组中。 data.txt文件如下所示: a 2016-10-03 Boston Type1 112 b 2016-05-02 Chicago Type2 150 c 2016-06-01 Denver Type3 1500 d 2016-08-26 NewYork Type4 80 int dl = CountFileLines("data.txt"); if (dl == 0) { System.exit(0); } String[][

基本上,我有一堆信息,我需要从文件中读取并将其放入2D数组中。 data.txt文件如下所示:

a 2016-10-03 Boston Type1 112
b 2016-05-02 Chicago Type2 150
c 2016-06-01 Denver Type3 1500
d 2016-08-26 NewYork Type4 80
int dl = CountFileLines("data.txt");
if (dl == 0) { System.exit(0); }
String[][] myArray = new String[dl][5];
myArray = applyFileDataToArray("data.txt", myArray);

// Display the contents of our 2D Array to Console...
for (int i = 0; i < myArray.length; i++) {
    System.out.println("\nROW " + (i+1) + ":");
    for (int j = 0; j < 5; j++) {
        System.out.println("\tColumn " + (j+1) + ":  " + myArray[i][j]);
    }
}

谢谢

您显然需要的是一个2D数组,它最终将由无限行组成,每行5列。要声明2D数组,首先需要确定希望每个列的数据类型。例如,让我们看看你的文件内容的第一行:

a 2016-10-03波士顿第112类

首先,我们有“a”,这是一种字符串数据类型

第二,我们有“2016-10-03”,这是一种日期数据类型

第三,我们有“Boston”,这也是一种字符串数据类型

第四,我们有“Type1”,这也是一种字符串数据类型

第五,最后是“112”,它很可能是一种整数数据类型

如果要在二维数组中维护这些特定数据类型,则需要将数组声明为对象:

对象[][]myArray={}

如果您希望仅将这些数据类型保持为字符串,而字符串实际上在文本文件中,那么您需要将2D数组声明为字符串:

字符串[][]myArray={}

这取决于您,您应该根据如何处理从数组中检索的元素数据来决定如何处理

首先需要确定需要多少行来对数组进行尺寸标注。为此,您需要知道数据文件中包含多少数据行。要做到这一点,我们需要一个简单的方法,以便获得这个数量。让我们创建一个方法来计算文本文件中的文本行数,我们将其称为countFileLines()

private static int countFileLines(String filePath) {
    try {
        int count = 0;
        try (InputStream inSt = new BufferedInputStream(new FileInputStream(filePath))) {
            byte[] c = new byte[1024];
            int readChars = 0;
            boolean NoNewLine = false;
            while ((readChars = inSt.read(c)) != -1) {
                for (int i = 0; i < readChars; ++i) {
                    if (c[i] == '\n') { ++count; }
                }
                NoNewLine = (c[readChars - 1] != '\n');
            }   
            if(NoNewLine) { ++count; }
            inSt.close();
        }
        return count;
    } 
    catch (FileNotFoundException ex) {
        System.out.println("countFileLines() Method ERROR - File Not Found!");
    } 
    catch (IOException ex) {
        System.out.println("countFileLines() Method ERROR - IO Exception Encountered\n" + ex.getMessage());
    } 
    return 0;
}
private static String[][] applyFileDataToArray(String filePath, String[][] myArray) {
    // declare and intialize a String variable to hold string 
    // data lines read from file.
    String line = "";
    // Declare and initialize a temporary 2D Array to fill with file data
    // and return.
    String[][] tmpArray = new String[myArray.length][myArray[0].length];
    // Declare and iniialize a Integer variable to be used as a incremental
    // index counter for our temporary 2D Array.
    int cnt = 0;
    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
        // Read in each line of the data text file so as to place each
        // line of data into the a temporary 2D String Array which will
        // be ulimately returned...
        while((line = br.readLine()) != null){
            // Skip past blank lines in the text file and only process file lines
            // which actually contain data.
            if (!line.equals("")) { 
                // Each line of data within the data text file consists
                // of a string with 5 data chunks each delimited with a 
                // whitespace. We place each data chunk into a String 
                // Array and then interate through this array and place 
                // each element into the 2D Array.
                String[] tok = line.split(" ");
                for (int i = 0; i < tok.length; i++) {
                    tmpArray[cnt][i] = tok[i];
                }
                // increment index counter...
                cnt++;
            }
        }
        // Data now acquired from file - Close the BufferReader
        br.close();
    } 
    // Trap IO Exceptions from the Bufferreader if any...
    catch (IOException ex) {
        System.out.println("\n\u001B[31mThe supplied data file could"
                         + " not be found!\n\u001B[39;49m" + filePath);
    }
    // Return filled 2D Array
    return tmpArray;
}
在这里,我们已经声明并初始化了2D字符串数组,以保存所提供数据文件中数据行所包含的行总数,并且我们已经将列设置为5,因为我们已经知道每个文件行由5个数据字符串块组成,这些数据块用空格分隔

现在我们需要做的就是读入每个数据文件行(行)并将每个字符串块(列)放入2D字符串数组中各自的元素中。我们需要制作一个简单的自定义方法来执行该任务。我们将其命名为applyFileDataToArray()

private static int countFileLines(String filePath) {
    try {
        int count = 0;
        try (InputStream inSt = new BufferedInputStream(new FileInputStream(filePath))) {
            byte[] c = new byte[1024];
            int readChars = 0;
            boolean NoNewLine = false;
            while ((readChars = inSt.read(c)) != -1) {
                for (int i = 0; i < readChars; ++i) {
                    if (c[i] == '\n') { ++count; }
                }
                NoNewLine = (c[readChars - 1] != '\n');
            }   
            if(NoNewLine) { ++count; }
            inSt.close();
        }
        return count;
    } 
    catch (FileNotFoundException ex) {
        System.out.println("countFileLines() Method ERROR - File Not Found!");
    } 
    catch (IOException ex) {
        System.out.println("countFileLines() Method ERROR - IO Exception Encountered\n" + ex.getMessage());
    } 
    return 0;
}
private static String[][] applyFileDataToArray(String filePath, String[][] myArray) {
    // declare and intialize a String variable to hold string 
    // data lines read from file.
    String line = "";
    // Declare and initialize a temporary 2D Array to fill with file data
    // and return.
    String[][] tmpArray = new String[myArray.length][myArray[0].length];
    // Declare and iniialize a Integer variable to be used as a incremental
    // index counter for our temporary 2D Array.
    int cnt = 0;
    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
        // Read in each line of the data text file so as to place each
        // line of data into the a temporary 2D String Array which will
        // be ulimately returned...
        while((line = br.readLine()) != null){
            // Skip past blank lines in the text file and only process file lines
            // which actually contain data.
            if (!line.equals("")) { 
                // Each line of data within the data text file consists
                // of a string with 5 data chunks each delimited with a 
                // whitespace. We place each data chunk into a String 
                // Array and then interate through this array and place 
                // each element into the 2D Array.
                String[] tok = line.split(" ");
                for (int i = 0; i < tok.length; i++) {
                    tmpArray[cnt][i] = tok[i];
                }
                // increment index counter...
                cnt++;
            }
        }
        // Data now acquired from file - Close the BufferReader
        br.close();
    } 
    // Trap IO Exceptions from the Bufferreader if any...
    catch (IOException ex) {
        System.out.println("\n\u001B[31mThe supplied data file could"
                         + " not be found!\n\u001B[39;49m" + filePath);
    }
    // Return filled 2D Array
    return tmpArray;
}
注意这行:tmpArray[cnt][1]=CDate(tok[1],“YYYY-MM-dd”)在上述代码中。此行包含另一个将日期字符串转换为日期数据类型的自定义方法。以下是cDate()方法的代码:

private static Date cDate(String val, String... expectedFormat) {
    //Usage:  Date d = cDate("2016-06-22", "yyyy-MM-dd");

    String dFormat = "dd/MM/yyyy";
    if (expectedFormat.length != 0) { dFormat = expectedFormat[0]; }

    SimpleDateFormat formatter = new SimpleDateFormat(dFormat, Locale.ENGLISH);
    try { 
        Date bdate = formatter.parse(val);
        return bdate;   // Default format is 01/01/2015
    }
    catch (ParseException e) { return null; }
}

希望这对您(和其他人)有所帮助。

很多要求,不是很多努力,也不是问题。请阅读帮助中心,了解如何提问以及我们的期望。感谢您对DevilsHnd的评论,它非常全面且易于理解。当我回家后,我会在我的程序中尝试实现所有这些。你就是那个人!
private static Date cDate(String val, String... expectedFormat) {
    //Usage:  Date d = cDate("2016-06-22", "yyyy-MM-dd");

    String dFormat = "dd/MM/yyyy";
    if (expectedFormat.length != 0) { dFormat = expectedFormat[0]; }

    SimpleDateFormat formatter = new SimpleDateFormat(dFormat, Locale.ENGLISH);
    try { 
        Date bdate = formatter.parse(val);
        return bdate;   // Default format is 01/01/2015
    }
    catch (ParseException e) { return null; }
}