Reputation: 103
I have the following code:
BufferedReader metaRead = new BufferedReader(new FileReader(metaFile));
String metaLine = "";
String [] metaData = new String [100000];
while ((metaLine = metaRead.readLine()) != null){
metaData = metaLine.split(",");
for (int i = 0; i < metaData.length; i++)
System.out.println(metaData[0]);
}
This is what's in the file:
testTable2 Name java.lang.Integer TRUE test
testTable2 age java.lang.String FALSE test
testTable2 ID java.lang.Integer FALSE test
I want the array to have at metaData[0]
testTable2
, metaData[1]
would be Name
, but when I run it at 0
I get testtable2testtable2testtable2
, and at 1
I'd get NameageID
and OutOfBoundsException
.
Any ideas what to do in order to get the result I want?
Upvotes: 3
Views: 55
Reputation: 424
Although my answer may not fit completely with your question. But as i can see, your file format is TSV or CSV. May be you should consider using OpenCSV for your problem.
The library will handle reading, splitting process for you.
Upvotes: 0
Reputation: 49606
Just print metaData[i]
instead of metaData[0]
and split each string by "[ ]+"
(that means "1 or more spaces"):
metaData = metaLine.split("[ ]+");
As a result, you will get the following arrays:
[testTable2, Name, java.lang.Integer, TRUE, test]
[testTable2, age, java.lang.String, FALSE, test]
[testTable2, ID, java.lang.Integer, FALSE, test]
The code snippet to the preceding output results:
while ((metaLine = metaRead.readLine()) != null) {
metaData = metaLine.split("[ ]+");
for (int i = 0; i < metaData.length; i++)
System.out.print(metaData[i] + " ");
System.out.println();
}
Also, I've written your task by using Java 8 and Stream API:
List<String> collect = metaRead
.lines()
.flatMap(line -> Arrays.stream(line.split("[ ]+")))
.collect(Collectors.toList());
And, finally, there is the most straight-forward way:
final int LINES, WORDS;
String[] metaData = new String[LINES = 5 * (WORDS = 3)]; // I don't like it
int i = 0;
while ((metaLine = metaRead.readLine()) != null) {
for (String s : metaLine.split("[ ]+")) metaData[i++] = s;
}
Upvotes: 3
Reputation: 164
Correct your code following line inside the for loop,
System.out.println(metaData[0]);
As
System.out.println(metaData[i]);
Upvotes: 0