使用Callback将String附加到文件

时间:2017-11-18 21:16:54

标签: java

我正在从数据库中读取数据,并希望使用回调从数据库中追加每一行数据。我设法使Callback工作,但我不知道如何将数据追加到文件中。这是我的代码。

主要

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();
        }
    }
}

我不确定如何将iAmDone()中的数据导入writeRStoFile()方法。我能够将数据打印到控制台。

1 个答案:

答案 0 :(得分:1)

我能想到的一种方法是将fw声明为FileIO中的成员变量。这样您就可以在fw.append(...)中致电iAmDone。 (您可能必须更改try-with-resources。)