How do I skip the first element from a String Array?
How do I skip the first element from a String Array?
Another quick approach is to control the line reads through flag like below:
public List<Beruf> fileRead(String filePath) throws IOException {
List<Beruf> berufe = new ArrayList<Beruf>();
String line = "";
try {
FileReader fileReader = new FileReader(filePath);
BufferedReader reader = new BufferedReader(fileReader);
Boolean firstLine = Boolean.TRUE;
while ((line = reader.readLine()) != null) {
if(firstLine) {
firstLine = Boolean.FALSE;
continue;
}
String[] attributes = line.split(";");
Beruf beruf = createBeruf(attributes);
berufe.add(beruf);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return berufe;
}
The easiest way to remove the header line would be to just read it before you enter your while loop.
String filePath = path;
FileReader fileReader = new FileReader(filePath);
BufferedReader reader = new BufferedReader(fileReader);
String headers = reader.readLine(); //This removes the first line from the BufferedReader
while ((line = reader.readLine()) != null) {
String[] attributes = line.split(";");
Beruf beruf = createBeruf(attributes);
berufe.add(beruf);
}
reader.close();
If you use java 8 or higher and are allowed to use streams you could also use the lines
method of the Files
class
Files.lines(Paths.get(filePath))
.skip(1) // skipping the headers
.map(line -> line.split(";"))
.map(attributes -> createBeruf(attributes))
.forEach(beruf -> berufe.add(beruf));