Issue
What I have : A constructor what's parameter is the filename
public class Main{
public static void main(String[] args) throws IOException {
Sad obj=new Sad("data.txt");
}
}
class Sad{
String [][] t=new String[3][3];
public Sad(File data) throws IOException {
String s= Files.readAllLines(Paths.get(data)).toString();
t=Arrays.stream(s.split("")).map(x->Arrays.stream(x.split(""))
.toArray())
.toArray(this.t[][]::new);
}
}
The text looks like this :
aaaa
bbbb
cccc
dddd
Solution
I believe it would be something like this:
String[][] string2Darray = null;
try {
java.nio.file.Path p = java.nio.file.Paths.get("data.txt");
string2Darray = java.nio.file.Files.lines(p)
.map((line) -> line.trim().split(""))
.toArray(String[][]::new);
}
catch (IOException ex) {
// Handle the exception the way you want...
}
// Display the 2D Array in Console Window.
if (string2Darray != null) {
System.out.println(Arrays.deepToString(string2Darray));
}
Based on the OP's comment to this Answer:
If you want to limit the number of lines (rows) to read (three as you asked for) and the number of columns in each line to place into the 2D array (two as you asked for) then change the code so it's like this (the code added is commented):
String[][] string2Darray = null;
try {
java.nio.file.Path p = java.nio.file.Paths.get(filePath);
string2Darray = java.nio.file.Files.lines(p).limit(3) // added .limit(3) for three lines only.
.map((line) -> line.trim().substring(0, 2).split("")) // added the substring() method.
.toArray(String[][]::new);
}
catch (IOException ex) {
// Handle the exception the way you want...
}
// Display the 2D Array in Console Window.
if (string2Darray != null) {
System.out.println(Arrays.deepToString(string2Darray));
}
Answered By - DevilsHnd
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.