如何修复我的文件编写器创建文件但将其留空?

How do I fix my file writer creating a file but leaving it empty?

我正在做一些 SQL 到 Java,但我遇到了纯粹的 Java 部分的障碍。 我正在使用 filewriter 创建和写入文本文件,它成功创建了文件。我可以在目录中看到它。没有错误或警告。

但是,文件是空的。

这是程序中的一段代码:

try{
    FileWriter x = new FileWriter("file.txt");
    rs = stmt.executeQuery("SELECT Emp_Name FROM Employees");
    while(rs.next()){
        String em = rs.getString("Emp_Name");
        x.write("\t" + em);
    } catch (IOException e){
        e.printStackTrace();
    }
}

这是完整的代码。

import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

/*
 * this program creates a table "users", inserts a row, retrieves the row and 
 * print it to the console
 * you have to provide the database name, the user id and the password
 * the database resides on cs1.utm.edu 
 */
public class MySQLProgram {

    public static void main(String[] args) {
        try {
            // load the driver
            Class.forName("com.mysql.jdbc.Driver");

        } catch (Exception ex) {
            System.out.println("Class not found exception: " + ex.getMessage());
        }

        Connection conn = null;
        try {
            // get the connection
            conn = DriverManager.getConnection(
                  // LINE REMOVED

            Statement stmt = null;
            ResultSet rs = null;
        ResultSet rt = null;
        ResultSet ru = null;
        ResultSet rv = null;
            // create a statement
            stmt = conn.createStatement();
            stmt.executeUpdate("use USER");
            // executes the statement --creates the table
            stmt.executeUpdate("CREATE TABLE Department(Dep_Code varchar(6)," + "Dep_Name varchar(55)," + "Phone_Ext int," + "PRIMARY KEY(Dep_Code))");
            
            stmt.executeUpdate("CREATE TABLE Employee(Emp_ID varchar(15)," + "Emp_Name varchar(20) NOT NULL," + "Salary int NOT NULL," + "MGR_ID varchar(10)," + "Dep_Code varchar(5) NOT NULL," + "PRIMARY KEY(Emp_ID)," + "FOREIGN KEY(Dep_Code) REFERENCES Department(Dep_Code))");
            
            stmt.executeUpdate("CREATE TABLE Project(Proj_Num varchar(12) NOT NULL," + "Proj_Name varchar(30) NOT NULL," + "Fee int NOT NULL," + "Due_Date DATE NOT NULL," + "PRIMARY KEY(Proj_Num))");
            stmt.executeUpdate("CREATE TABLE Assignment(Emp_ID varchar(10)," + "Proj_Num varchar(10) NOT NULL," + "Hours int NOT NULL," + "PRIMARY KEY(Emp_ID, Proj_Num)," + "FOREIGN KEY(Emp_ID) REFERENCES Employee(Emp_ID)," + "FOREIGN KEY(Proj_Num) REFERENCES Project(Proj_Num))");

        stmt.executeUpdate(" LOAD DATA LOCAL INFILE 'Department.dat' INTO TABLE Department FIELDS TERMINATED BY ','");
        stmt.executeUpdate(" LOAD DATA LOCAL INFILE 'Employee.dat' INTO TABLE Employee FIELDS TERMINATED BY ','");
        stmt.executeUpdate(" LOAD DATA LOCAL INFILE 'Project.dat' INTO TABLE Project FIELDS TERMINATED BY ','");
        stmt.executeUpdate(" LOAD DATA LOCAL INFILE 'Assignment.dat' INTO TABLE Assignment FIELDS TERMINATED BY ','");
        
        System.out.println("Display all results:");
        try {
        FileWriter x = new FileWriter("USER.txt");
        
        rs = stmt.executeQuery("SELECT Proj_Name, Proj_Num FROM Project");            
        while (rs.next()) {
            String em = rs.getString("Proj_Name");
            String me = rs.getString("Proj_Num");
            System.out.println("\t" + em + ",\t" + me);
            x.write("\t" + em + ",\t" + me);
        }// end for loop

        rt = stmt.executeQuery("SELECT Emp_ID, Emp_Name FROM Employee WHERE MGR_ID = 'e001' ");            
        while (rt.next()) {
            String Nem = rt.getString("Emp_ID");
            String Nme = rt.getString("Emp_Name");
            System.out.println("\t" + Nem + ",\t" + Nme);

            x.write("\t" + Nem + ",\t" + Nme);
        
        }


        ru = stmt.executeQuery("SELECT e.Emp_ID, e.Emp_Name FROM Employee e INNER JOIN Assignment a ON e.Emp_ID = a.Emp_ID GROUP BY e.Emp_ID HAVING COUNT(e.Emp_ID) > 1");            
        while (ru.next()) {
            String gem = ru.getString("Emp_Name");
            String gme = ru.getString("Emp_ID");
            System.out.println("\t" + gem + ",\t" + gme);
            x.write("\t" + gem + ",\t" + gme);
        }// end for loop

        stmt.executeUpdate("UPDATE Employee, Assignment SET Salary = Salary + 600 WHERE Employee.Emp_ID = Assignment.Emp_ID AND Assignment.Hours > 16");            
        rv = stmt.executeQuery("SELECT Salary FROM Employee");
        while (rv.next()) {
            String jem = rv.getString("Salary");
            System.out.println("\t" + jem);
            x.write("\t" + jem);
        
        }// end for loop
        }catch (IOException e){
        e.printStackTrace();
        }
        
    } catch (SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }

    }
}

使用 flush() 方法完成写入,完成后在 finally 块中关闭写入器。

我已经用 flush 更新了代码,还使用了 finally 子句来关闭编写器。

此外,您需要以附加模式打开 FileWriter 以写入来自其他查询的数据。

x = new FileWriter("USER.txt", true);

import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

/*
 * this program creates a table "users", inserts a row, retrieves the row and
 * print it to the console
 * you have to provide the database name, the user id and the password
 * the database resides on cs1.utm.edu
 */
public class MySQLProgram {

    public static void main(String[] args) {
        try {
            // load the driver
            Class.forName("com.mysql.jdbc.Driver");

        } catch (Exception ex) {
            System.out.println("Class not found exception: " + ex.getMessage());
        }

        Connection conn = null;
        try {
            // get the connection
            conn = DriverManager.getConnection(
                    // LINE REMOVED
                    
             Statement stmt = null;
            ResultSet rs = null;
            ResultSet rt = null;
            ResultSet ru = null;
            ResultSet rv = null;
            // create a statement
            stmt = conn.createStatement();
            stmt.executeUpdate("use USER");
            // executes the statement --creates the table
            stmt.executeUpdate("CREATE TABLE Department(Dep_Code varchar(6)," + "Dep_Name varchar(55)," + "Phone_Ext int," + "PRIMARY KEY(Dep_Code))");

            stmt.executeUpdate("CREATE TABLE Employee(Emp_ID varchar(15)," + "Emp_Name varchar(20) NOT NULL," + "Salary int NOT NULL," + "MGR_ID varchar(10)," + "Dep_Code varchar(5) NOT NULL," + "PRIMARY KEY(Emp_ID)," + "FOREIGN KEY(Dep_Code) REFERENCES Department(Dep_Code))");

            stmt.executeUpdate("CREATE TABLE Project(Proj_Num varchar(12) NOT NULL," + "Proj_Name varchar(30) NOT NULL," + "Fee int NOT NULL," + "Due_Date DATE NOT NULL," + "PRIMARY KEY(Proj_Num))");
            stmt.executeUpdate("CREATE TABLE Assignment(Emp_ID varchar(10)," + "Proj_Num varchar(10) NOT NULL," + "Hours int NOT NULL," + "PRIMARY KEY(Emp_ID, Proj_Num)," + "FOREIGN KEY(Emp_ID) REFERENCES Employee(Emp_ID)," + "FOREIGN KEY(Proj_Num) REFERENCES Project(Proj_Num))");

            stmt.executeUpdate(" LOAD DATA LOCAL INFILE 'Department.dat' INTO TABLE Department FIELDS TERMINATED BY ','");
            stmt.executeUpdate(" LOAD DATA LOCAL INFILE 'Employee.dat' INTO TABLE Employee FIELDS TERMINATED BY ','");
            stmt.executeUpdate(" LOAD DATA LOCAL INFILE 'Project.dat' INTO TABLE Project FIELDS TERMINATED BY ','");
            stmt.executeUpdate(" LOAD DATA LOCAL INFILE 'Assignment.dat' INTO TABLE Assignment FIELDS TERMINATED BY ','");

            System.out.println("Display all results:");
            FileWriter x = null;
            try {
                x = new FileWriter("USER.txt", true);
                rs = stmt.executeQuery("SELECT Proj_Name, Proj_Num FROM Project");
                while (rs.next()) {
                    String em = rs.getString("Proj_Name");
                    String me = rs.getString("Proj_Num");
                    System.out.println("\t" + em + ",\t" + me);
                    x.write("\t" + em + ",\t" + me);
                }// end for loop

                x.flush();
                rt = stmt.executeQuery("SELECT Emp_ID, Emp_Name FROM Employee WHERE MGR_ID = 'e001' ");
                while (rt.next()) {
                    String Nem = rt.getString("Emp_ID");
                    String Nme = rt.getString("Emp_Name");
                    System.out.println("\t" + Nem + ",\t" + Nme);

                    x.write("\t" + Nem + ",\t" + Nme);

                }

                x.flush();
                ru = stmt.executeQuery("SELECT e.Emp_ID, e.Emp_Name FROM Employee e INNER JOIN Assignment a ON e.Emp_ID = a.Emp_ID GROUP BY e.Emp_ID HAVING COUNT(e.Emp_ID) > 1");
                while (ru.next()) {
                    String gem = ru.getString("Emp_Name");
                    String gme = ru.getString("Emp_ID");
                    System.out.println("\t" + gem + ",\t" + gme);
                    x.write("\t" + gem + ",\t" + gme);
                }// end for loop
                x.flush();
                stmt.executeUpdate("UPDATE Employee, Assignment SET Salary = Salary + 600 WHERE Employee.Emp_ID = Assignment.Emp_ID AND Assignment.Hours > 16");
                rv = stmt.executeQuery("SELECT Salary FROM Employee");
                while (rv.next()) {
                    String jem = rv.getString("Salary");
                    System.out.println("\t" + jem);
                    x.write("\t" + jem);

                }// end for loop
                x.flush();
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                if(x != null){
                    try {
                        x.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        } catch (SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }

    }
}

写入文件后是否关闭文件写入器?

    try{
    FileWriter x = new FileWriter("file.txt");
    rs = stmt.executeQuery("SELECT Emp_Name FROM Employees");
    while(rs.next()){
        String em = rs.getString("Emp_Name");
        x.write("\t" + em);
    }
    x.close();
    } catch (IOException e){
        e.printStackTrace();
    }
}