简体   繁体   中英

Reading from a .txt into a 2D array

Sorry if my code seems bad, I'm not that experienced at programming. I need to transfer text from a .txt in the format of: Date-Name-Address-etc..

I'm reading in the file, then splitting the string with String.split("-"). I'm having trouble with the loops.

    try{
        File file = new File("testwrite.txt");
        Scanner scan = new Scanner(file);
        String[] test = scan.nextLine().split("-");
        while(r<100){
            while(c<6){
                data[r][c] = test[c];
                test = scan.nextLine().split("-");
                c++;
            }
            r++;
            c = 0 ;
        }
        System.out.println(data[1][5]);
    }catch(Exception e){
        System.out.println("Error: " + e.getMessage());
    }

Two dimensional array is just "array of arrays", so you can directly use split result to store the data of one line.

            File file = new File("testwrite.txt");
            Scanner scanner = new Scanner(file);
            final int maxLines = 100;
            String[][] resultArray = new String[maxLines][];
            int linesCounter = 0;
            while (scanner.hasNextLine() && linesCounter < maxLines) {
                resultArray[linesCounter] = scanner.nextLine().split("-");
                linesCounter++;
            }

It looks like you're calling scan.nextLine() too often. Every time you call scan.nextLine(), it advances the Scanner past the current line. Assuming your file has 100 lines, each with 6 "entries" (separated by "-"), I would move test = scan.nextLine().split("-"); to the end of the while loop (but still inside the loop) so that it gets called once per line.

Edit...

Proposed Solution: Given a file in the form,

abcxyz

abcxyz ... (100 times total)

Use this code:

try{
    File file = new File("testwrite.txt");
    Scanner scan = new Scanner(file);
    String[] test = scan.nextLine().split("-");
    while(r<100){
        while(c<6){
            data[r][c] = test[c];
            c++;
        }
        r++;
        c = 0 ;
        test = scan.nextLine().split("-");
    }
    System.out.println(data[1][5]);
}catch(Exception e){
    System.out.println("Error: " + e.getMessage());
}

Then use data[line][index] to access your data.

I split tab separated files using the following:

BufferedReader reader = new BufferedReader(new FileReader(path));
int lineNum = 0; //Use this to skip past a column header, remove if you don't have one
String readLine;
while ((readLine = reader.readLine()) != null) { //read until end of stream
    if (lineNum == 0) {
        lineNum++; //increment our line number so we start with our content at line 1.
        continue;
     }
     String[] nextLine = readLine.split("\t");

     for (int x = 0; x < nextLine.length; x++) {
         nextLine[x] = nextLine[x].replace("\'", ""); //an example of using the line to do processing.

         ...additional file processing logic here...
     }
}

Again, in my instance I am splitting on tabs (\\t) but you can just as easily split on - or any other character, aside from new line characters.

Per The Javadoc for readline() A line is considered to be terminated by any one of a line feed ('\\n'), a carriage return ('\\r'), or a carriage return followed immediately by a linefeed. .

Once you have your lines split up how you need, just assigned them to your array as required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM