Reputation: 2285
I have like these lines in a file:
101 xxx 3 yyy
102 aaa 2 bbb
103 ppp 3 qqq
104 iii 5 jjj
I want to put each elements of each line in an array, for example
int[] par1 = {101,102,103,104}
String[] par2 = {"xxx", "aaa", "ppp", "iii"}
int[] par3 = {3,2,3,5}
String[] par4 = {"yyy", "bbb", "qqq", "jjj"}
Upvotes: 0
Views: 113
Reputation: 135992
Something like this should work (didnt test)
List<String> lines = Files.readAllLines(Paths.get("1.txt"), StandardCharsets.UTF_8);
int[] par1 = new int[lines.size()];
String[] par2 = new String[lines.size()];
int[] par3 = new int[lines.size()];
String[] par4 = new String[lines.size()];
for(int i = 0; i < lines.size(); i++) {
String[] a = lines.get(i).split(" +");
par1[i] = Integer.parseInt(a[0]);
par2[i] = a[1];
par3[i] = Integer.parseInt(a[2]);
par4[i] = a[4];
}
Upvotes: 1
Reputation: 12621
Read lines with Guava / Apache Commons and so on:
Results in:
List<String> lines;
Next (using lines
):
List<Integer> par1 = new ArrayList();
List<String> par2 = new ArrayList();
List<Integer> par3 = new ArrayList();
List<String> par4 = new ArrayList();
try {
for(String line : lines) {
String[] elements = line.split(" ");
if(elements.length == 4) {
par1.add(Integer.valueOf(element[0]));
par2.add(element[1]));
par3.add(Integer.valueOf(element[2]));
par4.add(element[3]));
}
else {
throw new Exception("Conversion failed");
}
}
}
catch(NumberFormatException ex) {
throw new Exception("Conversion failed");
}
// Convert ArrayList to Array if you need to.
Upvotes: 2