简体   繁体   中英

One-line Java scanner to read a matrix from a file

I have been using this; A kind of one-liner:

public static String[] ReadFileToStringArray(String ReadThisFile) throws FileNotFoundException{
    return (new Scanner( new File(ReadThisFile) ).useDelimiter("\\A").next()).split("[\\r\\n]+");
}

To read a file with this type of contents(ie with string tokens):

abcd
abbd
dbcd

But, now my file contents are something like this:

1 2 3 4
1 2 2 4
1 5 3 7
1 7 3 8

I want these values to be read as integer.

I have seen these 1 , 2 and 3 questions but they do not answer to my question.

I have tried the following but failed:

public static int[][] ReadFileToMatrix(String ReadThisFile) throws FileNotFoundException{
    return (new Scanner( new File(ReadThisFile) ).useDelimiter("\\A").nextInt()).split("[\\r\\n]+");
}

Error message: Cannot invoke split(String) on the primitive type int . I understand the message and know it's horribly wrong :)

Can anybody suggest the right way to achieve this.

PS With all due respect, "NO" to solutions with loops.

Seems like an over complication of using classes when a basic BufferedReader with Integer.parseInt(line.split(" ")[n]); will do.

If you use Java 7 or higher you can use something like this. I cannot think of a way to do it in one line without a loop. Just put this into a methode and call it.

//Read full file content in lines
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

int NR_OF_COLUMNS = 4;
int NR_OF_ROWS = lines.size();

int[][] result = new int[NR_OF_ROWS][NR_OF_COLUMNS];

for(int rowIndex = 0; rowIndex < NR_OF_ROWS; rowIndex++)
{
    String[] tokens = lines.get(rowIndex).split("\\s+");  //split every line
    for(int columnIndex = 0; columnIndex < NR_OF_COLUMNS; columnIndex++)
        result[rowIndex][columnIndex] = Integer.parseInt(tokens[columnIndex]);   //convert every token to an integer
}
return result;

With Java 8, you can use Lambdas:

public static int[][] readFileToMatrix(String readThisFile) throws FileNotFoundException{
    return Arrays.stream((new Scanner( new File(readThisFile) ).useDelimiter("\\A").nextInt()).split("[\\r\\n]+")).mapToInt(Integer::parseInt).toArray();
}

Otherwise you cannot do it without a loop. You have a String[] array, and you want to call Integer.parseInt() for each element, one by one.

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