Useful Code Snipplets for Java

evertwagenaar.com logo

Introduction

Every Java programmer keeps his own library of useful code snippets. Here are some of mine:

  1. Writing text to a file
try {
  BufferedWriter out = new BufferedWriter(new 
  FileWriter("Path/to/file/name.txt*"));
        out.write("The String to write");
        out.close();
  } catch (IOException e) {
}
*The above example is UNIX / Linux. For Windows the '\' has a special meaning (Escape) and should therefore be escaped to '\\'. So a path could look like C:\\path\\to\\file\\name.txt. The UNIX notation will however work too. (C:/path/to/file/name.txt).
  1. Reading text from a file
try {
    BufferedReader in = new BufferedReader(new 
    FileReader("infilename"));
    String line;
  while ((str = in.readLine()) != null) {
    doSomething(line);
  }
     in.close();
  }  catch (IOException ioe){
}
Please note that paths to the filename should be the same as under 1.
  1. Connecting to a JDBC Database
Connection connection = null;
try {
// Load the JDBC driver (This example uses MySQL. 
// The driver.jar Must be on the Classpath).
String driverName = "org.gjt.mm.mysql.Driver"; // MySQL MM JDBC driver
Class.forName(driverName);

// Create a connection to the database
  String serverName = "localhost";
  String mydatabase = "mydatabase";
  String url = "jdbc:mysql://" + serverName +
  "/" + mydatabase; // a JDBC url
  String username = "username";
  String password = "password";
  connection = DriverManager.getConnection(url,
  username, password);

 } catch (ClassNotFoundException e) {
  // Could not find the database driver
 } catch (SQLException e) {
  // Could not connect to the database

Please note that this is just my personal top 3. I keep a few hundred of these useful ready-to-use useful snippets in my personal library. Please create a reaction to this post if you want to see more.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.