I am new to Java and not quite familiar with its design patterns.
I have tried to implement a CSV-File reader from scratch. The CSVFile constructor accepts the path to the file and a class which represents each datapoint (line in file). This class must implement the "fromLine" method (which accepts an array of Strings (each element being in a different column)) and the "toLine" method (which turns an object into a CSV-File line (String)). Both are described in the CSVDataPoint interface.
import java.util.List;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.io.FileReader;
import java.io.PrintWriter;
public class CSVFile
{
Class dp;
String path;
public CSVFile(String path, Class<? extends CSVDataPoint> dp)
{
this.path = path;
this.dp = dp;
}
public List load(int skip) throws Exception
{
List fields = new ArrayList<CSVDataPoint>();
int lineCount = 0;
try(BufferedReader br = new BufferedReader(new FileReader(path))){
String line;
while((line = br.readLine()) != null){
lineCount++;
if(lineCount > skip)
{
CSVDataPoint a = (CSVDataPoint) dp.newInstance();
fields.add(a.fromLine(line.split("\\,")));
}
}
}
return fields;
}
public void dump(List<CSVDataPoint> lines) throws Exception
{
String result = "";
PrintWriter writer = new PrintWriter(path, "UTF-8");
for(int n = 0; n < lines.size(); n++)
{
writer.println(lines.get(n).toLine());
}
writer.close();
}
}
CSVDataPoint interface:
public interface CSVDataPoint
{
Object fromLine(String[] line);
String toLine();
}
Although the code does work, I am not sure whether it is stylistically correct. Any criticism would be appreciated greatly.
Class.newInstance()
) albeit this is not the main purpose of the exercise \$\endgroup\$