<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>DBWS.NET &#187; java</title>
	<atom:link href="http://www.dbws.net/blog/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dbws.net/blog</link>
	<description>Software development mutterings and maybe a little something about myself.</description>
	<lastBuildDate>Wed, 09 Nov 2011 16:56:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Grails, jQuery and the jQuery Grid &#8211; Tutorial One</title>
		<link>http://www.dbws.net/blog/2010/03/21/grails-and-jquery-grid-tutorial/</link>
		<comments>http://www.dbws.net/blog/2010/03/21/grails-and-jquery-grid-tutorial/#comments</comments>
		<pubDate>Sun, 21 Mar 2010 16:05:17 +0000</pubDate>
		<dc:creator>Bolo</dc:creator>
				<category><![CDATA[Grails Tutorials]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[GRAILS]]></category>
		<category><![CDATA[grid]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jqgrid]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.dbws.net/blog/?p=39</guid>
		<description><![CDATA[I&#8217;ve been intending for quite some time to write a series of articles on my experiences so far with Grails based web applications. So I&#8217;m tackling this now whilst my experiences are still relatively fresh before my focus takes another direction. I don&#8217;t want to go into the why&#8217;s of using grails when there are [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been intending for quite some time to write a series of articles on my experiences so far with Grails based web applications. So I&#8217;m tackling this now whilst my experiences are still relatively fresh before my focus takes another direction.</p>
<p>I don&#8217;t want to go into the why&#8217;s of using grails when there are already many other frameworks out there but for me, I love Java for its power, vast number of libraries and community support available. I also love Ruby On Rails, for its convention over configuration benefits so when I discovered Grails is a kind of merge of the two, it quickly gained my interest. There are many cool features to Grails but to pinpoint a couple, not having to go through all the initial setting up of Spring, Hibernate, JPA etc is a real time saver, and how it allows you to use it&#8217;s own Groovy code alongside pure Java is something in my opinion both very clever and incredible beneficial to us web developers.</p>
<p>My target for these tutorials are not just for beginners to Grails but for anyone looking for quick how-to instructions to use Grails with various Ajax features such as displaying data in a jQuery grid, ajax filtering of data.</p>
<p>I do make the assumption however that you already know the basics of a grails based application and can already create, modify and deploy projects. I also don&#8217;t want to insist on any particular IDE for working on these tutorials, although I will be using IntelliJ&#8217;s IDEA IDE, Netbeans also has great Grails support but at the time of writing does not offer gsp tag completion. I cannot offer any other comment on the others as I am not familiar with Grails support in the other main contenders.</p>
<p>I also cannot recommend enough the combination of using Firefox as your browser with the Firebug plugin installed so you can keep an eye of your AJAX calls from your page to server. Firebug is a great tool that allows you to easily see what you are sending and what you are receiving.</p>
<p>Anyway enough introduction, let&#8217;s move onto the first tutorial of my series.</p>
<p>Grails, JQuery and the Jquery Grid.</p>
<p>In this tutorial I aim to show you how to use the jQuery Grid to present data to your users.</p>
<p>I am using Grails version 1.2 alongside MySQL database.</p>
<p>I will setup a mock up of a customer database for this example, so first you will need to create a new Grails project and setup your datasource details so you are all setup ready to go.</p>
<p>The first step after you&#8217;ve created your project and defined your datasource is to create a new Grails Domain class called Customer.   I&#8217;ve kept it simple, but with enough fields for us to create and display several columns in a grid.</p>
<pre class="brush: groovy; title: ; notranslate">class Customer {
  static constraints = {
    firstName(blank:false,maxSize:50)
    lastName(blank:false,maxSize:50)
    age(nullable:true)
    emailAddress(nullable:true)
  }

  String firstName
  String lastName
  Integer age
  String emailAddress
}</pre>
<p>Once your class is defined, you should go ahead and generate the customer controller and corresponding views.</p>
<p>Now would be a good time to add some test data so we have something we can use to manipulate our views. A handy shortcut to create test data here is to edit the bootstrap groovy file so we can create some data at the time our application is launched. This is a technique I often use to preload testdata.</p>
<pre class="brush: groovy; title: ; notranslate">class BootStrap {

def init = { servletContext -&amp;gt;
  // if we have an empty customer database,
  // create some test data
  if (Customer.count() == 0) {
    new Customer(
      firstName:'John', lastName:'Smith',
      age:27,
      emailAddress:'john@somewhere.com'
    ).save()

    new Customer(
      firstName:'Frank', lastName:'Malone',
      age:37,
      emailAddress:'frank@somewhere.com'
    ).save()

    new Customer(
      firstName:'Dave', lastName:'Brown',
      age:34,
      emailAddress:'dave@somewhere.com'
    ).save()

    new Customer(
      firstName:'Barney', lastName:'Rubble',
      age:44,
      emailAddress:'barney@somewhere.com'
    ).save()
  }
}

def destroy = { }
}
</pre>
<p>I will also change the urlmappings so when we launch the application our default page is the customer index view :</p>
<pre class="brush: groovy; title: ; notranslate">class UrlMappings {
  static mappings = {
    &quot;/$controller/$action?/$id?&quot;{
      constraints {
      // apply constraints here
    }
  }
  &quot;/&quot;(controller:&quot;customer&quot;,action:&quot;index&quot;)
  &quot;500&quot;(view:'/error')
  }
}</pre>
<p>So try running the application now and you should see the default presented list on the customer page. So far so good.</p>
<p>Before we create the necessary adjustments to use a jQuery grid, you will first need to download the required javascript librarys as well css styles for your grid from the following links:</p>
<p>jQuery <a href="http://docs.jquery.com/Downloading_jQuery#Current_Release">latest release</a></p>
<p>jQuery Grid <a href="http://www.trirand.com/blog/?page_id=6">latest release</a> &#8211; contains the necessary javascript and css (ui.grid.css). Copy the ui.grid.css to the web-app/css folder.</p>
<p>jQuery UI css themes : <a href="http://jqueryui.com/download">theme download</a> &#8211; this is a great site that allows you to visual different UI themes for jquery widgets/plugins before downloading the necessary css/images.</p>
<p>I download the &#8216;min&#8217; versions of the javascript librarys to cut down download time for the user. jquery.jqGrid.min.js and jquery-1.3.2.min.js both go into the web-app/js folder.<br />
You theme will be downloaded as a zip file, you will need to copy the jquery-ui-1.7.2.custom.min.js script into your applications js folder and the contents of the css folder go into your web-app/css folder. For the purpose of this tutorial I downloaded the ui-lightness theme.</p>
<p>So now I want to switch from the default list view, to a jQuery Grid to present our customer data.</p>
<p>Edit your Customer/list.gsp, and perform the following.</p>
<p>1. Include our new javascript librarys by adding the includes into the  head section. Our css style sheet should also be reference by also adding to the head section. Your head section should then contain the following:</p>
<pre class="brush: groovy; title: ; notranslate">
&lt;link rel=&quot;stylesheet&quot; href=&quot;${resource(dir:'css',file:'main.css')}&quot; /&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;${resource(dir:'css',file:'ui.jqgrid.css')}&quot; /&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;${resource(dir:'css/ui-lightness',file:'jquery-ui-1.7.2.custom.css')}&quot; /&gt;
&lt;g:javascript library=&quot;jquery-1.3.2.min&quot;/&gt;
&lt;g:javascript library=&quot;jquery-ui-1.7.2.custom.min&quot;/&gt;
&lt;g:javascript library=&quot;grid.locale-en&quot;/&gt;
&lt;g:javascript library=&quot;jquery.jqGrid.min&quot;/&gt;
</pre>
<p>2. Remove the tag and contents of</p>
<div class="list">tag as well as the paginator tag that immediately follows it.3. I usually create page fragments for my jquery specific grids but for this example we will just place the code directly into the main list page.</p>
<p>You have to create a table element to hold our grid, as well as div element to go at the end of the table to display record count, paginator.</p>
<p>Insert the following jquery Grid definition. This defines a very basic grid which will be rendered when the page loads in the browser. Notice the url parameter, url:&#8217;jq_customer_list&#8217;. This is the url from which the grid will load its data. I have also specified the format of the data will be JSON. These parameters lead us to our next stage, we need to create the necessary function in our Customer controller that will return the data.</p>
<pre class="brush: groovy; title: ; notranslate">
&lt;!-- table tag will hold our grid --&gt;
&lt;table id=&quot;customer_list&quot; class=&quot;scroll jqTable&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot;&gt;&lt;/table&gt;
&lt;!-- pager will hold our paginator --&gt;
&lt;div id=&quot;customer_list_pager&quot; class=&quot;scroll&quot; style=&quot;text-align:center;&quot;&gt;&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;&gt;// &lt;![CDATA[
/* when the page has finished loading.. execute the follow */
$(document).ready(function () {
  jQuery(&quot;#customer_list&quot;).jqGrid({
  url:'jq_customer_list',
  datatype: &quot;json&quot;,
  colNames:['First Name','Last Name','Age','Email Address','id'],
  colModel:[
    {name:'firstName'},
    {name:'lastName'},
    {name:'age'},
    {name:'email'},
    {name:'id'}
  ],
  pager: jQuery('#customer_list_pager'),
  viewrecords: true,
  gridview: true
  });
});
// ]]&gt;&lt;/script&gt;</pre>
<p>4. Create the jq_customer_list action in the Customer controller to respond to the grids request for JSON data.</p>
<p>As we are returning JSON type data, you must add an import to the top of the controller : import grails.converters.JSON</p>
<p>Note that the order of the fields must match the order in which we defined the order in the colModel and colNames in the grid definition. The minimal code to return the data is as follows:</p>
<pre class="brush: groovy; title: ; notranslate">
def jq_customer_list = {
  def customers = Customer.list()
  def jsonCells = customers.collect {
    [cell: [it.firstName,
    it.lastName,
    it.age,
    it.emailAddress], id: it.id]
  }
  def jsonData= [rows: jsonCells]
  render jsonData as JSON
}</pre>
<p>5. Try and run your application, if all succeeded you should be presented with your customer data in a nice looking grid.</p>
<div id="attachment_40" class="wp-caption aligncenter" style="width: 310px"><a rel="attachment wp-att-40" href="http://www.dbws.net/blog/2010/03/21/grails-and-jquery-grid-tutorial/customer_list/"><img class="size-medium wp-image-40" title="customer list image" src="http://www.dbws.net/blog/wp-content/uploads/2010/03/customer_list-300x136.jpg" alt="customer list presented in a jquery grid" width="300" height="136" /></a><p class="wp-caption-text">Browser showing customer list presented in jquery grid</p></div>
<p>The entire project for this tutorial can be downloaded <a href="http://www.dbws.net/blog/attach/Tutorial1.zip">here</a>.</p>
<p>In my next tutorial I will take what we have done so far, and implement ajax pagination and table sorting when the user clicks on a column header.</p>
<p>Interested in learning more grails?  Head over and join up at the <a title="Grails Forum - Grails Discussion and support group" href="http://www.grailsforum.co.uk" target="_blank">grails forum</a></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.dbws.net/blog/2010/03/21/grails-and-jquery-grid-tutorial/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Grails 2 DataAccessResourceFailureException Solved</title>
		<link>http://www.dbws.net/blog/2010/02/15/grails-2-dataaccessresourcefailureexception-solved/</link>
		<comments>http://www.dbws.net/blog/2010/02/15/grails-2-dataaccessresourcefailureexception-solved/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 14:15:20 +0000</pubDate>
		<dc:creator>Bolo</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[DBCP]]></category>
		<category><![CDATA[GRAILS]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Tomcat]]></category>

		<guid isPermaLink="false">http://www.dbws.net/blog/?p=29</guid>
		<description><![CDATA[For those using MYSQL and have either updated to grails version 2 or starting with grails 2 and have run into this exception then this solution works perfectly well for me. The problem is releated to Grails running out of connections to MySQL over time, &#38; not freeing stale connections.Â  I believe it happens when [...]]]></description>
			<content:encoded><![CDATA[<p>For those using MYSQL and have either updated to grails version 2 or starting with grails 2 and have run into this exception then this solution works perfectly well for me.</p>
<p>The problem is releated to Grails running out of connections to MySQL over time, &amp; not freeing stale connections.Â  I believe it happens when there hasn&#8217;t been activity for over 8 hours, which in my case happened everyday due to the overnight period.</p>
<p>So what we should be doing is managing our own database connection pool.Â Â  I use Tomcat 6 on my production servers so the following solution is specifically for tomcat 6.</p>
<p>What we need to do is first change our application configuration so it sets up a database connection pool through tomcat.Â  And secondly we need to tweak the configuration so that we validate the connection is present periodically and removed stale connections.</p>
<p>The first thing then is to define the connection pool in &lt;your application dir&gt;/web-app/META-INF/context.xml</p>
<p>A typical context.xml would be :</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;Context path=&quot;/MyApplication&quot;&gt;
&lt;Resource
 auth=&quot;Container&quot;
 driverClassName=&quot;com.mysql.jdbc.Driver&quot;
 maxActive=&quot;20&quot;
 maxIdle=&quot;10&quot;
 maxWait=&quot;-1&quot;
 removeAbandoned=&quot;true&quot;
 name=&quot;jdbc/myAppsPool&quot;
 type=&quot;javax.sql.DataSource&quot;
 url=&quot;jdbc:mysql://localhost:3306/Database_Name&quot;
 username=&quot;user&quot;
 password=&quot;password&quot;
 validationQuery=&quot;SELECT '1'&quot;
 removeAbandonedTimeout=&quot;60&quot;
 logAbandoned=&quot;true&quot;/&gt;
&lt;/Context&gt;</pre>
<p>This alone will create the necessary database connection pool when you application is deployed.</p>
<p>All thats left to do now is to change your datasource configuration to refer to the connection pool so in your DataSource.groovy file, locate the production section and alter it to refer to the new pool, e.g :</p>
<pre class="brush: groovy; title: ; notranslate">production {
  dataSource {
    pooled = false
    dbCreate = &quot;update&quot;
    jndiName = &quot;java:comp/env/jdbc/myAppsPool&quot;
  }
}</pre>
<p>That should solve any of those DataAccessResourceFailureExceptions from now on.[</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dbws.net/blog/2010/02/15/grails-2-dataaccessresourcefailureexception-solved/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sorting the request Parameters</title>
		<link>http://www.dbws.net/blog/2008/01/24/sorting-the-request-parameters/</link>
		<comments>http://www.dbws.net/blog/2008/01/24/sorting-the-request-parameters/#comments</comments>
		<pubDate>Thu, 24 Jan 2008 14:19:33 +0000</pubDate>
		<dc:creator>Bolo</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[getParameterMap]]></category>
		<category><![CDATA[getParameters]]></category>
		<category><![CDATA[J2EE]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[request]]></category>
		<category><![CDATA[sorting]]></category>

		<guid isPermaLink="false">http://www.dbws.net/blog/2008/01/24/sorting-the-request-parameters/</guid>
		<description><![CDATA[This snippet is from a servlet which acts as a generic form posting utility used throughout some of my sites. Irrelevant of the dressing of the JSP, it can be presenting the user a form for any number of reasons, but in each case when submitted the form contents will be emailed to my site [...]]]></description>
			<content:encoded><![CDATA[<p>This snippet is from a servlet which acts as a generic form posting utility used throughout some of my sites.  Irrelevant of the dressing of the JSP, it can be presenting the user a form for any number of reasons, but in each case when submitted the form contents will be emailed to my site admins.    The initial problem I encountered whilst writing was that when you iterate the submitted request parameters, the order they come out will be at random.   So you can either parse the request query itself OR give your form fields names which when alphabetically sorted will make sense.  The latter is the quickest method.. Anyway here is the servlet, It uses collections to first construct a List, which you can then use Collections to sort, and finally use Collections again to create a new Enumeration of the sorted list.  Enough babble heres the code :</p>
<pre>
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{ 

StringBuffer sb = new StringBuffer();
sb.append("The following information was posted via the website;\n\n");

// Sort the list
List paramList = Collections.list(request.getParameterNames());
Collections.sort(paramList);
Enumeration sortedList = Collections.enumeration(paramList);

// iterate the list and append to a StringBuffer
for (Enumeration e = sortedList; e.hasMoreElements();) {

String paramName = (String) e.nextElement();
String[] values = request.getParameterValues(paramName);
sb.append(paramName + " = " + values[0] + "\n");
sb.append("\n");
}

// Email admin the sorted form contents
Utils.Send_SMTP("mailer@dbws.net", Utils.adminEmails, "Website Form Submission", sb.toString());

request.getRequestDispatcher("thankyou.jsp").forward(request, response);
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.dbws.net/blog/2008/01/24/sorting-the-request-parameters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Binary file processing with Java</title>
		<link>http://www.dbws.net/blog/2007/02/28/binary-file-processing-with-java/</link>
		<comments>http://www.dbws.net/blog/2007/02/28/binary-file-processing-with-java/#comments</comments>
		<pubDate>Wed, 28 Feb 2007 18:55:18 +0000</pubDate>
		<dc:creator>Bolo</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.dbws.net/blog/?p=8</guid>
		<description><![CDATA[A task arose recently from one my clients requesting me to help process some binary files they had. They needed me to create a new file based on their input file with where all occurrences of a specific byte get replaced with a different specific byte. No problem I thought, but deciding which method to [...]]]></description>
			<content:encoded><![CDATA[<p>A task arose recently from one my clients requesting me to help process some binary files they had. They needed me to create a new file based on their input file with where all occurrences of a specific byte get replaced with a different specific byte. No problem I thought, but deciding which method to use to perform the reading and replacing of the values proved to be not immediately obvious.</p>
<p>There are a several approaches to reading and writing files, as well as several approaches to the replacing of values, in fact Java almost always offers a multitude of solutions to a problem.</p>
<p>So i decided to embark upon a little experiment to see what I could find to be the most efficient method.</p>
<p>Firstly I decided to create my own test data. To do so I just simply created a file containing many random bytes. I chose a random number between 0 and 32 as that most closely matched my original client requirement. CreateTest.java will create a 10mb file.</p>
<p>I wrote 4 little tests during the experiment,  trying String replacement, byte comparison and replacement and buffered readers/writers. The result surprised me.</p>
<p><strong>Method 1.</strong></p>
<p>My first method I decided to read in the data into a 4k buffer using a FileInputStream.  I then create a new String object based upon the bytes read and replace the old value with the new value using String.replace(). Then the bytes from the String are written to a FileOutputStream.</p>
<p><strong>Method 2</strong></p>
<p>The second method I simply wondered if I could save any processing time by doing all the functions of Method1 for comparison and replacing on as little code lines as possible, as I expected this did not make any real difference.</p>
<p><strong>Method 3</strong></p>
<p>For method 3 I used the same method of reading the file by reading into a buffer using FileInputStream but rather than use the String replace function, I first compare the bytes and then write either the old or the new value into a second buffer. The result of this change was encouraging, the time taken to process the file was about 20-40% the time it took using the String object.</p>
<p><strong>Method 4</strong></p>
<p>Feeling encouraged by the results in method 3, I thought now if I use the Buffered Input &amp; Output Stream objects java gives us, then I was sure to reap extra benefits, But the time taken rose dramatically.</p>
<p>Timing Results.</p>
<p>To come up with these results, I ran the classes from the command prompt 10 times each and recorded the average time taken.</p>
<p>Method1 : 500 ms<br />
Method2 : 700 ms<br />
Method3 : 150 ms<br />
Method4 : 2800 ms</p>
<p>I wondered if I could tweak the buffer size in Method 3 to see what difference that makes when processing the files, To be honest I donâ€™t know why I picked 4kb in the first place, it just happens to be habit when defining buffer sizes.</p>
<p>I tried 1k, 16k, 32k, 100k, and 512k.</p>
<p>With a 1k buffer the average time was 280 ms.<br />
A 16k buffer gave me an average of 90 ms.<br />
A 32k buffer gave me an average of 78 ms.<br />
A 100k buffer averages out at 125 ms.<br />
And the 512k buffer was back to roughly 200ms.</p>
<p>So using a 32k buffer gave me the best results.</p>
<p>Conclusion.</p>
<p>I was a little surprised that the time taken rose so dramatically when using the buffered reader and writer object. I must admit my understanding of the buffering objects is not at an expert level but I did expect to see improvement, else why use them if controlling the buffer myself proves to be so much more efficient.</p>
<p>Below you will find all the code used in these tests:</p>
<div class="source">
<p>/*<br />
* CreateTest.java<br />
*<br />
* Created on 04 February 2007, 11:19<br />
*<br />
* Purpose: To create a binary test file used in file processing tests.<br />
*/</p>
<p>import java.io.FileOutputStream;<br />
import java.util.Random;</p>
<p>/**<br />
*<br />
* @author DAVE<br />
*/<br />
public class CreateTest {</p>
<p>static final long fileSize = 10 * 1024 * 1024; // Lets make it 10mb<br />
static final String outFile = &#8220;testfile.dat&#8221;;<br />
private static Random rn = new Random();</p>
<p>/** Creates a new instance of CreateTest */<br />
public CreateTest() {<br />
}</p>
<p>public static void main(String[] args) throws Exception{<br />
// Open file for output<br />
FileOutputStream out = new FileOutputStream(outFile);</p>
<p>for (int i = 0; i &lt; fileSize; i++) {<br />
// Get Random int between 0 &amp; 32<br />
int idx = rand(0,32);<br />
out.write(idx);<br />
}<br />
out.close();<br />
System.out.println(&#8220;testfile.dat created.&#8221;);<br />
}</p>
<p>// get Random number<br />
private static int rand(int lo, int hi) {<br />
int n = hi &#8211; lo + 1;<br />
int i = rn.nextInt() % n;<br />
if (i &lt; 0)<br />
i = -i;<br />
return lo + i;<br />
}<br />
}</p>
</div>
<div class="source">/*<br />
* Method1.java<br />
*<br />
* Created on 02 February 2007, 17:49<br />
*<br />
* Process binary file, byte by byte performing a replace<br />
* using Strings &amp; replace() function.<br />
*<br />
*/</p>
<p>import java.io.FileInputStream;<br />
import java.io.FileOutputStream;<br />
import java.util.Date;</p>
<p>public class Method1 {</p>
<p>public Method1() {<br />
}</p>
<p>public static void main(String[] args) throws Exception{<br />
Date startTime = new Date();<br />
Date endTime;</p>
<p>String inFile = &#8220;testfile.dat&#8221;;<br />
String outFile = &#8220;outputfile.dat&#8221;;</p>
<p>char oldValue = 0&#215;00;<br />
char newValue = 0xFF;<br />
final int bufferSize = 4 * 1024; // 4kb buffer<br />
byte[] buffer = new byte[bufferSize];</p>
<p>FileInputStream in = new FileInputStream(inFile);<br />
FileOutputStream out = new FileOutputStream(outFile);</p>
<p>String s = null;<br />
int read = in.read(buffer);<br />
while (read &gt;= 0) {<br />
if (read &gt; 0) {<br />
s = new String(buffer);<br />
if (s.length() != read) {<br />
s = s.substring(0,read);<br />
}<br />
s = s.replace(oldValue,newValue);<br />
out.write(s.getBytes());<br />
}<br />
read = in.read(buffer);<br />
}</p>
<p>out.close();<br />
in.close();<br />
endTime = new Date();</p>
<p>System.out.println(&#8221; Method 1  &#8211; time taken (ms) : &#8220;+(endTime.getTime() &#8211; startTime.getTime()));</p>
<p>}<br />
}</p>
</div>
<div class="source">/*<br />
* Method2.java<br />
*<br />
* Created on 02 February 2007, 17:49<br />
*<br />
* Process binary file, byte by byte performing a replace<br />
* using Strings &amp; replace() function.<br />
*/</p>
<p>import java.io.FileInputStream;<br />
import java.io.FileOutputStream;<br />
import java.util.Date;</p>
<p>public class Method2 {</p>
<p>public Method2() {<br />
}</p>
<p>public static void main(String[] args) throws Exception{<br />
Date startTime = new Date();<br />
Date endTime;</p>
<p>String inFile = &#8220;testfile.dat&#8221;;<br />
String outFile = &#8220;outputfile.dat&#8221;;</p>
<p>char oldValue = 0&#215;00;<br />
char newValue = 0xFF;<br />
final int bufferSize = 4 * 1024; // 4kb buffer<br />
byte[] buffer = new byte[bufferSize];</p>
<p>FileInputStream in = new FileInputStream(inFile);<br />
FileOutputStream out = new FileOutputStream(outFile);</p>
<p>int read = in.read(buffer);<br />
while (read &gt;= 0) {<br />
if (read &gt; 0) {<br />
out.write(new String(buffer,0,read).replace(oldValue,newValue).getBytes());<br />
}<br />
read = in.read(buffer);<br />
}</p>
<p>out.close();<br />
in.close();</p>
<p>endTime = new Date();<br />
System.out.println(&#8221; Method 2  &#8211; time taken (ms) : &#8220;+(endTime.getTime() &#8211; startTime.getTime()));</p>
<p>}<br />
}</p>
</div>
<div class="source">/*<br />
* Method3.java<br />
*<br />
* Created on 02 February 2007, 17:49<br />
*<br />
* Process binary file, byte by byte performing a replace<br />
* using byte comparison only<br />
*/</p>
<p>import java.io.FileInputStream;<br />
import java.io.FileOutputStream;<br />
import java.io.OutputStreamWriter;<br />
import java.util.Date;</p>
<p>public class Method3 {</p>
<p>public Method3() {<br />
}</p>
<p>public static void main(String[] args) throws Exception{<br />
Date startTime = new Date();<br />
Date endTime;</p>
<p>String inFile = &#8220;testfile.dat&#8221;;<br />
String outFile = &#8220;outputfile.dat&#8221;;</p>
<p>byte oldValue = (byte)0&#215;00;<br />
byte newValue = (byte)0xFF;</p>
<p>final int bufferSize = 32 * 1024; // 32kb buffer</p>
<p>byte[] buffer = new byte[bufferSize];<br />
byte[] cBuffer = new byte[bufferSize];</p>
<p>FileInputStream in = new FileInputStream(inFile);<br />
FileOutputStream out = new FileOutputStream(outFile);</p>
<p>int read = in.read(buffer);<br />
while (read &gt;= 0) {<br />
if (read &gt; 0) {<br />
for (int i = 0; i &lt; read; i++) {<br />
if (buffer[i] == oldValue)<br />
cBuffer[i] = newValue;<br />
else<br />
cBuffer[i] = buffer[i];<br />
}<br />
out.write(cBuffer,0,read);<br />
}<br />
read = in.read(buffer);<br />
}</p>
<p>out.close();<br />
in.close();<br />
endTime = new Date();<br />
System.out.println(&#8221; Method 3  &#8211; time taken (ms) : &#8220;+(endTime.getTime() &#8211; startTime.getTime()));<br />
}<br />
}</p>
</div>
<div class="source">/*<br />
* Method4.java<br />
*<br />
* Created on 02 February 2007, 17:49<br />
*<br />
* Process binary file, byte by byte performing a replace<br />
* using buffered streams<br />
*/</p>
<p>import java.io.BufferedInputStream;<br />
import java.io.BufferedOutputStream;<br />
import java.io.FileInputStream;<br />
import java.io.FileOutputStream;<br />
import java.util.Date;</p>
<p>public class Method4 {</p>
<p>public Method4() {<br />
}</p>
<p>public static void main(String[] args) throws Exception{<br />
Date startTime = new Date();<br />
Date endTime;</p>
<p>String inFile = &#8220;testfile.dat&#8221;;<br />
String outFile = &#8220;outputfile.dat&#8221;;</p>
<p>byte oldValue = (byte)0&#215;00;<br />
byte newValue = (byte)0xFF;</p>
<p>BufferedInputStream bis = null;<br />
BufferedOutputStream bos = null;</p>
<p>bis = new BufferedInputStream(new FileInputStream(inFile));<br />
bos = new BufferedOutputStream(new FileOutputStream(outFile));</p>
<p>int theByte;<br />
while ((theByte = bis.read()) != -1) {<br />
if (theByte != oldValue)<br />
bos.write(theByte);<br />
else<br />
bos.write(newValue);<br />
}</p>
<p>bos.close();<br />
bis.close();<br />
endTime = new Date();<br />
System.out.println(&#8221; Method 4  &#8211; time taken (ms) : &#8220;+(endTime.getTime() &#8211; startTime.getTime()));<br />
}<br />
}</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.dbws.net/blog/2007/02/28/binary-file-processing-with-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

