Java I/O

From Wiki
Revision as of 21:45, 31 January 2011 by Scott (talk | contribs) (Database)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Streams

Reading a text file (Core Java, p645):

BufferedReader in = new BufferedReader(new FileReader("employee.txt"));
...
String s;
while ((s = in.readLine()) != null){
..do stuff with s...
}

Reading Unicode characters from a text file:

BufferedReader in = new BufferedReader(new FileReader("employee.txt"));
...
char c;
while ((c = (char)in.read()) >= 0){
..do stuff with c...
}

Reading bytes from a generic data file:

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName);
int n;
while ((n = bis.read()) > -1){
..do stuff with n..
}

Reading from the command line (p66)

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
...
String s = in.readLine();
..do stuff with s...

Writing to a text file:

PrintWriter out = new PrintWriter(new FileWriter("employee.txt"));
println("some text");
println("some more text");
out.flush();   // won't write until you call this

PrintWriter and Autoflush: If this is on, the file is written to whenever you call println(). There are two constructors:

PrintWriter(String filename)

has autoflush off by default. In this case, you must call

out.flush();

to get the output written!

Use

PrintWriter(String filename, boolean autoflush)

to turn autoflush on.

The PrintWriter is buffered, so you don't need to throw in a buffered writer.

FileWriter and Appending: use

new FileWriter("employee.txt", true)

to append.

Database

(need driver file on your classpath)

Example:

import java.sql.*;
...
public static void testConnection(){
//  String url = "jdbc:odbc:tk1dev" ;
//  String url = "jdbc:oracle:thin:@es01:1521:tk1DEV";
    String url = "jdbc:mysql://localhost/test";
    Connection con = null;
    try {
//      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//      Class.forName("oracle.jdbc.driver.OracleDriver");
        Class.forName("com.mysql.jdbc.Driver");
    } catch(java.lang.ClassNotFoundException e) {
        e.printStackTrace();
        return;
    }
    try {
        con = DriverManager.getConnection(url, "tk", "xxxxxxxx");
        Statement statement = con.createStatement();
        //String queryString = "select sysdate from dual";
        String queryString = "select now()";
        ResultSet rs = statement.executeQuery(queryString);
        while (rs.next()){
            System.out.println("result is "+rs.getTimestamp(1));
        }
    } catch(SQLException e) {
        e.printStackTrace();
    } finally {
        try{
            con.close();
        } catch(SQLException e) {
            e.printStackTrace();
        }
    }
}