Reputation: 1575
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(i.e. 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.
P.S. With all due respect, "NO" to solutions with loops.
Upvotes: 0
Views: 1287
Reputation: 15758
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.
Upvotes: 0
Reputation: 1911
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;
Upvotes: 0
Reputation: 25
Seems like an over complication of using classes when a basic BufferedReader
with Integer.parseInt(line.split(" ")[n]);
will do.
Upvotes: 1