I'm reading data from a DB and like to appended each row of data from the DB using a Callback. I've managed to get the Callback working but I don't know how I will get it append the data to file. Here is my code.
Main
public class Main {
public static void main(String[] args) {
FileIO fileIO = new FileIO();
fileIO.writeRStoFile();
}
}
FileIO
public class FileIO implements DBAccess.CallBack {
public void writeRStoFile() {
DBAccess dbAccess = new DBAccess(this);
String fileName = "/result.csv";
try (FileWriter fw = new FileWriter(fileName)) {
System.out.println("Starting data download from DB...");
dbAccess.readDB();
// HERE I LIKE TO APPEND EACH ROW TO THE FILE
fw.append('\n');
System.out.println("Finished data download from DB...");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void iAmDone(String row) {
System.out.println("Row: " + row);
}
}
DBAccess
public class DBAccess {
public interface CallBack {
public void iAmDone(String row);
}
private final CallBack callBack;
public DBAccess(CallBack callBack) {
this.callBack = callBack;
}
public void readDB() {
String url = "jdbc:Cobol:////Dev/Project Files/DatAndCpyFiles";
try (Connection con = DriverManager.getConnection(url, "", "");
Statement stmt = con.createStatement())
{
stmt.setFetchSize(10);
Class.forName("com.hxtt.sql.cobol.CobolDriver").newInstance();
String sql = "select * from PROFS";
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData resultSetMetaData = rs.getMetaData();
int iNumCols = resultSetMetaData.getColumnCount();
for (int i = 1; i <= iNumCols; i++) {
callBack.iAmDone(resultSetMetaData.getColumnLabel(i) + ";");
}
String field;
while (rs.next()) {
String row = "";
for (int i = 1; i <= iNumCols; i++) {
field = rs.getString(i);
field = field.trim() + ";";
row = row + field;
}
callBack.iAmDone(row);
}
rs.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
I'm not sure how I get the data from iAmDone() into the writeRStoFile() method. I'm able to print the data to the console.
One way that I can think of is to declare
fwas a member variable inFileIO. That way you can callfw.append(...)iniAmDone. (You might have to change the try-with-resources then.)