0

I am trying to write data from a database into a text file.

The text file remains empty. I tried to deg. Here is the code:

public void writeText()
{
     try
    {
        Class.forName("com.mysql.jdbc.Driver");
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    final String DB_URL ="jdbc:mysql://mis-sql.uhcl.edu/gattupalliv3940";
    Connection conn = null;
    Statement stat  = null;
    ResultSet rs = null;
    try
    {
        conn = DriverManager.getConnection(DB_URL,"gattupalliv3940","1552688");
        stat = conn.createStatement();
        rs = stat.executeQuery("select * from student_2");
        FileWriter fw = new FileWriter("data.txt");
        BufferedWriter bw = new BufferedWriter(fw);
        String line ="";
        while(rs.next())
        {
            line = rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getDouble(3);
            bw.write(line);
            bw.newLine();
        }
        bw.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            conn.close();
            rs.close();
            stat.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}
4
  • Why aren't you using JPA for database access? Is this a Java SE project? Commented Jul 27, 2017 at 21:29
  • Please state what you already tried to solve the issue, else there will be a huge ping pong on some basic debugging techniques. First comes here: Try to minimize the code and enclose the problem. Does your file writing code even work? Did you try it without all that SQL stuff, just test if your code is able to write a given String into a file. After that check if your database really contains something. Then check if your query result is not empty and so on. Somewhere must be the error, find it by enclosing it. Commented Jul 27, 2017 at 21:58
  • Its a Java EE project. Result set is not empty. It tried the same code in SE project and it worked. Commented Jul 28, 2017 at 3:06
  • Don't write the real password on any public place. Writing or reading of a file has completely nothing to do with Java EE. Check to see if the database connection is actually acquired or not, sout the value of ResultSet (stored in line), check out the location of the text file data.txt etc. Commented Jul 28, 2017 at 4:23

3 Answers 3

1

If you aren't getting any errors and the file is empty, the only thing that can be happening is your while(rs.next()) line must be returning false the first time through; meaning you aren't getting anything from the database.

Have you stepped through the code to verify which lines are executing and which ones are not?

I suspect that the file isn't being written to where you expect since you aren't specifying a directory. I created a simple test and the file was written out to the Tomcat's directory at ...\springsource\vfabric-tc-server-developer-2.6.4.RELEASE\spring-insight-instance\wtpwebapps\Junk\data.txt (my Project is named Junk). Below is my code (without the database stuff):

@RequestMapping(value="/")
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws IOException{

    writeText(request.getRealPath("data.txt"));

    return new ModelAndView("home");
}

public void writeText(String path) {
    BufferedWriter bw = null;
    try {
        FileWriter fw = new FileWriter(path);
        bw = new BufferedWriter(fw);
        String line = "this is only a test";
        bw.write(line);
        bw.newLine();
    }
    catch(Exception e) {
        e.printStackTrace();
    } finally {
        if( bw != null ) {
            try {
                bw.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

In here can use library called JOConnection. import this library to your project externally.

In the beginning create a file.

 File myDb=new File("file_name");

then access that file db by using this code

 Database db=Connection.openConnection(myDb);

then get data to write to db as list of objects.

 ArrayList<Items> itmDetails=  (ArrayList<Items> )db.getList("Items");

then add those data to the file db

       db.addList("Items", itmDetails);

finally

  Connection.save(); 

Comments

0

I have the exact same problem when trying to write log to a file from Oracle.

FileOutputStream works for me! Hopefully this works for you. I have no idea why is PrintWriter not working. Must be setup of oracle...

List<String> logs = new LinkedList<String>();       
String filepath = "xxx.txt";
System.out.println(filepath);
OutputStream os = null;
try{
    for(int i = 0; i < logs.size(); i++) {
        os = new FileOutputStream(filepath,true);
        os.write(("\n"+logs.get(i)).getBytes(), 0, ("\n"+logs.get(i)).length());            
    }               
    } catch (IOException e) {
         e.printStackTrace();
    } finally{
         try {
             os.close();
         } catch (IOException e) {
             e.printStackTrace();
     }
}   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.