HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

"Programming with I/O Streams: Part 2"
Volume: 4 Issue: 1, p. 52

	

Listing 1:
 
Type.java<import java.io.*;

/** Displays contents of a file (e.g. java Type app.ini) */
public class Type
{
    public static void main(String args[])
                       throws Exception
    {
       // Open input/output and setup variables
       FileReader  fr = new FileReader(args[0]);
       PrintWriter pw = new PrintWriter(System.out, true);
       char c[]       = new char[4096];
       int  read      = 0; 

       // Read (and print) till end of file
       while ((read = fr.read(c)) != -1)
          pw.write(c, 0, read);

       // Close shop
       fr.close();
       pw.close();
    }
}

Listing 2:

Copy.javamport java.io.*;

/** Copies a file (e.g. java Copy config.sys config.bak) */
public class Copy
{
    public static void main(String args[])
                       throws Exception
    {
       if (args.length < 2)
       {
          System.err.println("usage: java Copy InputFile OutputFile");
          System.exit(1);
       }

       // Open input/output and setup variables
       FileReader fr = new FileReader(args[0]);
       FileWriter fw = new FileWriter(args[1]);
       char c[]      = new char[4096];
       int  read     = 0, total = 0;

       // Read (and print) till end of file
       while ((read = fr.read(c)) != -1)
       {
          fw.write(c, 0, read);
          total += read;
       }

       // Close shop
       fr.close();
       fw.close();

       System.out.println(total + " bytes copied");
    }
}

Listing 3: Config.java

import java.io.*;
import java.util.Properties;


/** Displays a config file (e.g. java Config app.ini) */
public class Config
{
    public static void main(String args[])
                       throws Exception
    {
       // Open input/output and setup variables
       FileInputStream fis = new FileInputStream(args[0]);
       Properties p        = new Properties();

       p.load(fis);
       fis.close();

       // Display email id property
       System.out.println("email = " + p.getProperty("email"));
    }

Listing 4: Run.java import java.io.*;


/* Displays output of a program (e.g. java Run "ls -l") */
public class Run
{
    public static void main(String args[])
                       throws Exception
    {
       Process p      = Runtime.getRuntime().exec("ls -l");
       InputStream is = p.getInputStream();
       byte b[]       = new byte[4096];
       int  c;

       while ((c = is.read(b)) != -1)
          System.out.write(b, 0, c);

       p.destroy();
    }
}

Listing 5: ServletTest.java
 
import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;



/** Demo use of streams in Servlets
  * (e.g. http://myhost.com/servlet/ServletTest/
  */
public class ServletTest
             extends HttpServlet
{
    public void doPost(HttpServletRequest req, HttpServletResponse res)
                throws ServletException, IOException
    {
       InputStream  is = req.getInputStream();
       OutputStream os = res.getOutputStream();
       byte b[]        = new byte[4096];
       int  c;

       res.setContentType("text/plain");
       while ((c = is.read(b)) != -1)
          os.write(b, 0, c);
    }


    public void doGet(HttpServletRequest req, HttpServletResponse res)
                throws ServletException, IOException
    {
       res.setContentType("text/html");

       ServletOutputStream sos = res.getOutputStream();
       sos.println("Please use the POST method for this servlet!");
    }

Listing 6: SendData.java

import java.io.*;
import java.net.*;


/** Transmit patient data to Data Center in Virginia
  * (e.g. java SendData remoteHost hospitalName patientDataDir)
  */
public class SendData
{
    private static final String DONE=".done";


    public static void main(String args[])
                       throws Exception
    {
       // Check arguments
       if (args.length < 3)
       {
          System.err.println("usage: java SendData remoteHost hospitalName patientDataDir");
          System.exit(1);
       }

       // Initialize variables
       String remoteHost   = args[0],
              hospitalName = args[1],
              dataDir      = args[2],
              fileList[]   = null,
              patientFile  = null;

       // Ensure that directory exists
       File f = new File(dataDir);
       if (!f.exists() || !f.isDirectory())
       {
           System.err.println(dataDir + " is an invalid directory");
           return;
       }

       // Ensure there are files to process
       fileList = f.list();
       if (fileList == null || fileList.length < 1)
       {
           System.err.println("No files to process");
           return;
       }

       Socket s          = null;
       BufferedWriter bw = null;
       FileReader fr     = null;
       File origFile     = null, renamedFile = null;
       char c[]          = new char[4096];
       int read, patientsProcessed = 0;

       // Process each file
       for (int i=0; i < fileList.length; i++)
       {
          // Do not process previously processed or empty files
          origFile = new File(dataDir, fileList[i]);
          if (fileList[i].endsWith(DONE) || origFile.length() < 1)
          {
              System.out.println("Skipping file " + fileList[i]);
              continue;
          }

          patientFile = origFile.getName();

          // Open connection to remote host and process file
          s  = new Socket(remoteHost, 55555);
          bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
          fr = new FileReader(origFile);

          System.out.println("Transmitting " + patientFile + " ...");

          // Send hospital name on first line
          bw.write(hospitalName, 0, hospitalName.length());
          bw.newLine();

          // Send patient name name on second line
          bw.write(patientFile, 0, patientFile.length());
          bw.newLine();

          // Send data as remaining lines
          while ((read = fr.read(c)) != -1)
             bw.write(c, 0, read);

          // Close shop
          bw.flush();
          fr.close();
          bw.close();
          s.close();

          // Rename original file to indicate it was processed
          renamedFile = new File(dataDir, fileList[i] + DONE);
          origFile.renameTo(renamedFile);

          patientsProcessed++;
       }

       System.out.println(patientsProcessed + " patients processed");
    }
}

Listing 7: ReceiveDataServer.java

import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.zip.GZIPOutputStream;


/** Server for receiving client data (e.g. java ReceiveDataServer) */
public class ReceiveDataServer
{
    public static void main(String args[])
                       throws Exception
    {
        ServerSocket server = new ServerSocket(55555);
        Socket       client = null;

        // Display server info
        System.out.println(server);

        // Continuosly wait for client connections and process their data
        while (true)
        {
           // Accept a client connection, spawn a thread for it
           // and go back to listening for other clients
           client = server.accept();
           (new ProcessData(client)).start();
        }
    }
}



class ProcessData
      extends Thread
{
    Socket s = null;

    public ProcessData(Socket client)
    {
       s = client;
    }


    // This method is invoked when running in a separate thread
    public void run()
    {
       System.out.println("Thread started for client: " + s);

       DataInputStream  dis = null;
       GZIPOutputStream gos = null;
       String hospitalName  = null,
              patientName   = null,
              fileName      = null;

       try
       {
          // Receive incoming data using following protocol:
          // 1st line = hospital name
          // 2nd line = patient name
          // Remaining bytes are the patient’s data

          dis = new DataInputStream(s.getInputStream());
          hospitalName = dis.readLine();
          patientName  = dis.readLine();
          fileName     = patientName + ".gz";
          gos          = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
          byte b[]     = new byte[4096];
          int  c, total= 0;


          System.out.println("Reading and saving data as GZIP file for " + patientName);
          while ((c = dis.read(b)) != -1)
          {
             gos.write(b, 0, c);
             gos.finish();
             total += c;
          }

          // Close output file and socket
          gos.close();
          s.close();

          if (total < 1)
          {
             System.out.println("0 bytes received, no database action required");
             return;
          }

          // Now store GZIP/input file in database using JDBC
          storeInDatabase(hospitalName, patientName, fileName);
       }
       catch (Exception e)
       {
          System.err.println("Database error: " + e.getMessage());
          e.printStackTrace();
          return;
       }

       System.out.println("Done processing " + patientName);
       System.out.flush();
    }


    /**
      * Store data in a table named "Patients" with the following columns:
      * 1. hospitalName char(50)
      * 2. patientName char(50)
      * 3. patientData text (or memo in MS-Access)
      */
    private void storeInDatabase(String hospitalName,
                                 String patientName,
                                 String fileName)
                 throws Exception
    {
       System.out.println("Ready to save data in database for " + patientName);
       Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
       Connection        conn = DriverManager.getConnection("jdbc:odbc:Patients", "admin", "");
       PreparedStatement stmt = null;
       ResultSet rslt         = null;
       String sql             = null;
       int count;

       // See if record already exists
       sql   = " SELECT COUNT(*) FROM Patients WHERE patientName = ?";
       stmt  = conn.prepareStatement(sql);
       stmt.setString(1, patientName);
       rslt  = stmt.executeQuery();
       rslt.next();
       count = rslt.getInt(1);
       rslt.close();
       stmt.close();

       // Get file info and open input stream
       File fileInfo  = new File(fileName);
       int fileLength = (int)fileInfo.length();
       InputStream is = new FileInputStream(fileName);

       // Do either an INSERT or UPDATE 
       if (count < 1)
       {
           System.out.println("Record not found, doing an INSERT");
           sql = " INSERT INTO Patients"
               + " (hospitalName, patientName, patientData)"
               + " VALUES (?, ?, ?)";
           stmt = conn.prepareStatement(sql);
           stmt.setString(1, hospitalName);
           stmt.setString(2, patientName);
           stmt.setBinaryStream(3, is, fileLength);
       }
       else
       {
           System.out.println("Record found, doing an UPDATE");
           sql = " UPDATE Patients"
               +    " SET patientData = ?"
               +  " WHERE patientName = ?";
           stmt = conn.prepareStatement(sql);
           stmt.setBinaryStream(1, is, fileLength);
           stmt.setString(2, patientName);
       }

       // Close shop
       stmt.executeUpdate();
       stmt.close();
       conn.close();
       is.close();
   }
}</pre>
        </td>
    </tr>
</table>

Listing 8: ShowDbData.java
    
import java.net.*;
import java.sql.*;
import java.util.zip.GZIPInputStream;


/** Displays patient data in DB (e.g. java ShowDbData JohnSmith) */
public class ShowDbData
{
    public static void main(String args[])
                       throws Exception
    {
       // Check arguments
       if (args.length < 1)
       {
          System.err.println("usage: java ShowDbData patientName");
          System.exit(1);
       }

       // Initialize variables
       String patientName  = args[0];

       Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
       Connection        conn = DriverManager.getConnection("jdbc:odbc:Patients", "admin", "");
       PreparedStatement stmt = null;
       ResultSet rslt         = null;
       String sql             = null;
       InputStream is         = null;
       byte b[]               = new byte[4096];
       int count;

       // Query for data
       sql   = " SELECT patientData FROM Patients WHERE patientName = ?";
       stmt  = conn.prepareStatement(sql);
       stmt.setString(1, patientName);
       rslt  = stmt.executeQuery();
       rslt.next();
       is    = rslt.getBinaryStream(1);

       // For some reason, GZIP doesn’t work directly with the 
       // stream returned by JDBC, so we’ll use a temp file
       File tmpFile         = new File(patientName + ".tmp");
       FileOutputStream fos = new FileOutputStream(tmpFile);
       while ((count = is.read()) != -1)
          fos.write(count);
       is.close();

       // Decompress and display data to stdout
       is = new GZIPInputStream(new FileInputStream(tmpFile));
       while ((count = is.read(b)) != -1)
          System.out.write(b, 0, count);

       // Close shop
       is.close();
       fos.close();
       rslt.close();
       stmt.close();
       conn.close();

       // Delete temp file
       tmpFile.delete();
   }
}

      
 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.