Posts filed under 'java'
Java Rebel saves me ….
- All “.class” classes inside the usual classpath (
WEB-INF/classes, etc). will provide the best JavaRebel experience.
Add the following to JVM command line (note that it is important that the JAR would be named “javarebel.jar”)
" -noverify -javaagent:/path/to/javarebel.jar " for example: set JAVA_OPTIONS=-noverify -javaagent:d:\javarebel\javarebel.jar
Add comment September 15, 2008
IDE battle , Netbeans 6 and eclipse 3.3
The competition between these two IDE’s play mind games in programmer’s mind these days. Choosing right IDE for your needs makes us to think twice . Eventually , we choose the best or even not !. I have been using eclipse for around 2 to 3 years on my development , and i found comfortable , later i heard about Sun’s Netbeans IDE . So i tried to experiment on version 5 which was long back i used . And i found little bit programmer friendly , ofcourse it gives same basic thing what eclipse can do . But what highlighted me is much ease use of plugin’s and integration with multi-language capability. Afterall , we end up coding in java even we choose any “IDE’s” .
There is perhaps no area of programming tools where competition is as intense as in the Java IDE market. Even though there are only four primary players — Eclipse, NetBeans, IntelliJ IDEA, and Oracle JDeveloper (Rational and CodeGear JBuilder build on Eclipse).The competition is most intense between Eclipse, NetBeans, and IntelliJ IDEA, likely because those products have the most active communities of users and those users tend to be personally attached to their preferred environment. Of the three, only Eclipse and NetBeans are free and open source.
I will mention One of the weirdest thing about eclipse and nebeans i came across . Eclipse installation consists of unzipping a download file. As long as you have Java 5 installed on your system, simply clicking on the Eclipse icon will get you started. Once you do, however, you are confronted with an annoyance particular to Eclipse — workspaces. If you later create a project and don’t place it at the first-level subdirectory of your Eclipse workspace, you receive an error message.
Installing NetBeans is better but not. For example, if at the time of installation on Windows, the JDK is not specifically located in C:\Program Files\Java, the installation fails with a dialog stating that no instance of the JDK was found. NetBeans does not ask where the JDK is located: it simply doesn’t run. It does give the option of re-running the installation from a command line and specifying the location using a command-line switch, but it provides no example.
The editing experience
Table 1. Editing features
| Feature | Eclipse 3.3 | NetBeans 6.0 |
|---|---|---|
| Code refactorings | 22 | 17 |
| Generates | Getters/Setters and similar, javadoc, unit tests, UML | Getters/Setters and similar, javadoc, unit tests, UML, BPEL |
| Spell checking comments and literals | Yes | No |
| Other Java-related editors | JSP, JSF, XML, HTML | JSP, JSF, XML, HTML |
Language support
Eclipse officially supports C/C++, COBOL, PHP, and AspectJ. Its dynamic language toolkit project unofficially supports Ruby.
NetBeans supports C/C++ and two versions of Ruby: regular Ruby and JRuby, which runs on the JVM rather than the Ruby VM.
Plugins
Eclipse dominates in all aspects of plugins. Nearly all new commercial plugins that ship for Java (such as recent Java products from Agitar and Enerjy) ship for Eclipse first. Actually, most of them ship for Eclipse only. A few are ported to NetBeans, but not many.
Rate ‘em
Personal preference plays a uniquely important role in choosing the development environment . Consequently, any head-to-head comparison that results in a rating will be useful to only the fraction of readers who weigh the given features the same way the reviewer does. Below list tells about the weightings for the features I think are important. You should change these weightings to reflect your preferences and then calculate your own final score.
Table 2. NetBeans 6.0 vs. Eclipse 3.3: Rated
| Feature | Weighting | Eclipse 3.3 | NetBeans 6.0 |
|---|---|---|---|
| Ease of use/editing features | 40% | 2.8 | 3.6 |
| Scripting/other languages | 10% | 3.0 | 3.6 |
| Enterprise support | 20% | 3.2 | 3.0 |
| Plugin ecosystem | 30% | 3.8 | 2.7 |
| Total score | 3.20 | 3.21 |
During that time, Eclipse-based IDEs have regularly won top honors, while versions of NetBeans have lagged badly. This is the first review in which NetBeans truly stands on a par with Eclipse, and depending on your weightings could finish ahead. NetBeans has definitely arrived and is worthy of careful evaluation.
6 comments June 12, 2008
Creating Dynamic image
Some website prompt you to enter dynamic number generated in the image , especially when you are filling registration form ….and usually found at the end of registration form. User must enter exactly same number or alphanumeric character found on the image , this is because to make sure that Human is using webapplication and keeping away from robots/sypwares or any hacking software’s to fill the form.
Below is simple java code for how to generate dynamic image .This is a sample servlet that dynamically generates JPEG images. Currently all image properties are hard-coded, but it should be trivial to provide a jsp form to collect them (e.g., color, font, dimensions, messages). The generated image contains dynamic data such as the appserver name, and OS name.
import com.sun.image.codec.jpeg.JPEGCodec;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class ImageServlet extends HttpServlet {
private static final int WIDTH = 450;
private static final int HEIGHT = 200;
private static final Color BACKGROUND_COLOR = new Color(100,149,237);
private static final Color COLOR = new Color(0,0,139);
private static final Font FONT = new Font("Times New Roman", Font.BOLD, 46);
private static final Font FOOT_FONT = new Font("Courier", Font.ITALIC, 14);
private static final Color FOOT_COLOR = Color.BLACK;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("image/jpg");
ServletOutputStream out = response.getOutputStream();
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_BYTE_INDEXED);
Graphics graphics = image.getGraphics();
graphics.setColor(BACKGROUND_COLOR);
graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
graphics.setColor(COLOR);
graphics.setFont(FONT);
graphics.drawString("Hello World!", 10, HEIGHT/2); //insert String or any random number
graphics.setFont(FOOT_FONT);
graphics.setColor(FOOT_COLOR);
graphics.drawString("Created by " + getServletContext().getServerInfo(), 10, HEIGHT - 30);
graphics.drawString("for http://javahowto.blogspot.com/ on " + System.getProperty("os.name"), 10, HEIGHT - 10);
JPEGCodec.createJPEGEncoder(out).encode(image);
}
}
The web.xml file is as simple as declaring and mapping a servlet:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>image</servlet-name>
<servlet-class>ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>image</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
And i hope you know rest of the things to deploy the webapp ......
output...


1 comment May 21, 2008
Started something new, Google AJAX API!
Well its been long i have tried something new or learn something new …. Today i started with Google’s AJAX Search API . I started with simple local search using simple search and i learned how to embed samething in my blog see this example : http://madhucm.blogspot.com.
I would have included in this blog but i dont know how to edit <body> tag. And also it doesn’t allow you to do … well it doesn’t matter however.
The first thing i did was getting the JAX Search API key so that it is valid within a single directory on your web server. And after getting the key, i tweaked my blog template , and finally included the script. Well if you know javascript it damn easy to create you own search.
ex: var localSearch = new google.search.LocalSearch();
searchControl.addSearcher(localSearch); // This is local search
searchControl.addSearcher(new google.search.WebSearch()); // search on web
searchControl.addSearcher(new google.search.VideoSearch()); // video search
searchControl.addSearcher(new google.search.BlogSearch()); // blog search….
You can also customize your view , like :- TABBED, LINEAR .
// create a drawOptions object var drawOptions = new GdrawOptions(); // tell the searcher to draw itself in linear mode drawOptions.setDrawMode(GSearchControl.DRAW_MODE_LINEAR); or drawOptions.setDrawMode(GSearchControl.DRAW_MODE_TABBED); searchControl.draw(element, drawOptions);
more info:http://code.google.com/apis/ajaxsearch/
1 comment May 16, 2008
Logging GC activity how to
An easy low cost method to check the activity of the garbage collector in the JVM is to tell the JVM to create an activity log. This is achieved for Sun JVMs using the non-standard command line option “-Xloggc:file_name“. This will tell the JVM to create a log file with a content similar with this:
0.806: [GC 8064K->1211K(30912K), 0.0051670 secs]
1.363: [GC 9275K->1856K(30912K), 0.0061070 secs]
1.944: [GC 9920K->2602K(30912K), 0.0115890 secs]
2.351: [GC 10666K->3289K(38976K), 0.0083440 secs]
3.159: [GC 19417K->4316K(38976K), 0.0325310 secs]
3.948: [GC 20444K->5735K(56192K), 0.0083630 secs]
35.812: [GC 37671K->7896K(56512K), 0.0152040 secs]
525.368: [GC 39832K->8066K(89600K), 0.0082710 secs]
As one can guess the log entries show the time of the garbage collection activity, the memory before and after and the duration of the garbage collection. This can prove very useful when monitoring the activity of a server application for memory leaks and for memory activity.
If the information about the garbage collection activity is only needed at the console the “-XX:+PrintGC” and “-XX:+PrintGCDetails” options can be used. The last one will produce an output with more details lke this one:
[GC [PSYoungGen: 33584K->1312K(33600K)] 36545K->6656K(55104K), 0.0141310 secs]
…
Heap
PSYoungGen total 33920K, used 8802K [0×00002aaac91c0000, 0×00002aaacd790000, 0×00002aaad39c0000)
eden space 30976K, 19% used [0×00002aaac91c0000,0×00002aaac97840a8,0×00002aaacb000000)
from space 2944K, 98% used [0×00002aaacd4b0000,0×00002aaacd784978,0×00002aaacd790000)
to space 4096K, 0% used [0×00002aaaccf90000,0×00002aaaccf90000,0×00002aaacd390000)
PSOldGen total 21504K, used 5344K [0×00002aaab41c0000, 0×00002aaab56c0000, 0×00002aaac91c0000)
object space 21504K, 24% used [0×00002aaab41c0000,0×00002aaab46f8340,0×00002aaab56c0000)
PSPermGen total 21248K, used 19211K [0×00002aaaaedc0000, 0×00002aaab0280000, 0×00002aaab41c0000)
object space 21248K, 90% used [0×00002aaaaedc0000,0×00002aaab0082d50,0×00002aaab0280000)
The behavior of the logging option seems to produce identical results as “-XX:+PrintGC” even if personally I would’ve expect more details in the log file. Maybe this will change in a future version of Java.
4 comments May 15, 2008
Using Dynamic Method Invocation to “Script” Java
Although Java isn’t thought of as a dynamic language now a days, what with Ruby and Groovy being all the rage, Java does have support for dynamic features.
A Use Case for Dynamic Java
Currently I’m wrapping about a hundred EJB 2.1 LocalHome classes in DAO’s, and having them transform local EJB entities into POJO’s. Much of the code is largely boiler plate. Actually it’s mind numbingly boiler plate. Here’s a sample of wrapping a finder:
public Endowment findById ( String id ) {
try {
// get the local home
EndowmentLocalHome endowmentLH = EndowmentUtil.getLocalHome ();
// lookup the entity
EndowmentLocal endowmentL = endowmentLH.findByPrimaryKey ( id );
// return the entity
return createEndowment ( endowmentL );
} catch ( Exception e ) { throw new VRRemoteException ( e ); }
}
So, five lines of code just to call a finder, then there’s the createEndowment() method that actually does the transformation into a POJO. Additionally every method is cluttered with try {} catch {} constructs, further blurring the intent of the code.
By using reflection and dynamic method calls I’ve been able to reduce the boilerplate to:
public Member findById ( String id ) {
return (Member) mixin.find ("findById", new Object[] { id } );
}
If by chance my finder returns a Collection, all I need to do is cast the result to Collection.
Each DAO is specific to a “type.” Not type as in a Class, but type as in a “business type,” ie the snipped deals with the “Endowment” type. For each type there are a number of EJB 2.1 and POJO classes collaborating to make the whole thing work. For the Endowment type the critical classes are:
- EndowmentUtil: A utility class for looking up local and remote home interfaces using JNDI. This utility class shields us complete from JNDI.
This class is generated by XDoclet. - EndowmentLocalHome: The local home for the Endowment EJB.
- EndomentLocal: A local EJB entity of an endowment.
- EndowmentValue: A value bean representing an endowment. This is generated by XDoclet.
- EndowmentDAO: An interface for a persistence agnostic data access object.
- EndowmementDAOEjbImpl: An implementation of EndowmentDAO that wraps the EJB 2.1 LocalHome.
- Endowment: A POJO in a new clean package that has no connection to our old EJB 2.1/XDoclet code.
The other thing we’re doing is making our POJO’s transparently navigable, just like JPA entities are when they are managed by an EntityManager. (ie: We can do contactMechanism.getParty().getMember().)
The major issue is that I had repeating patterns like the findById() example above that are the same except that the “type” differed. The convention is the same, over and over. Reflection and my dynamic method calling to the rescue. (NB: This app needs to run on a Java 1.4 server, otherwise I’d have taken a look at generics to solve some of these issues.)
The Solution
Using the findById sample the pattern is easily identifyable:
public Endowment findById ( String id ) {
try {
// get the local home
EndowmentLocalHome endowmentLH = EndowmentUtil.getLocalHome ();
// lookup the entity
EndowmentLocal endowmentL = endowmentLH.findByPrimaryKey ( id );
// return the entity
return createEndowment ( endowmentL );
} catch ( Exception e ) { throw new VRRemoteException ( e ); }
}
Simplifying this to pseudo code can help in seeing the pattern:
public #TYPE# findById ( String id ) {
try {
// get the local home
#TYPE#LocalHome localHome = #TYPE#Util.getLocalHome ();
// lookup the entity
#TYPE#Local localEjb = localhome.findByPrimaryKey ( id );
// return the entity
return create#TYPE# ( localEjb );
} catch ( Exception e ) { throw new VRRemoteException ( e ); }
}
We can even simplify this further, because the pattern is really the same with any finder. Look up a #TYPE#Util, call getLocalHome() on it, getting a #TYPE#LocalHome, call the finder method and transform the result into a POJO.
public #TYPE# find (Object[] args ) {
try {
// get the local home
#TYPE#LocalHome localHome = #TYPE#Util.getLocalHome ();
// lookup the entity
#TYPE#Local localEjb = localhome.find ( args );
// return the entity
return create#TYPE# ( localEjb );
} catch ( Exception e ) { throw new VRRemoteException ( e ); }
}
We call some find method with some collection of arguments, represented by the Object[], which could also be absent for an no-argument finder.
With the pattern identified let’s “script” it using the dynamic method calling and the fact that the related class names all follow a convention.
Here’s the code that will call any finder using the pattern above:
public Object find (String finder, Object[] args) {
Object result = sendMessage (finder, getLocalHome(), args);
if (result instanceof Collection) {
try {
Collection originalResultList = (Collection) result;
// If the result is empty there is nothing to convert. Return the empty collection.
if (originalResultList.size() == 0) {
return result;
}
Collection resultList = new ArrayList ( originalResultList.size () );
for (Iterator itr = originalResultList.iterator (); itr.hasNext (); ) {
Object ejb = itr.next ();
resultList.add (createPojo (ejb) );
}
result = resultList;
} catch (Exception e) {
throw new VRUtilityException ("ERROR: Post-processing a collection into POJO's for type = '" + getType() + "'.", e);
}
} else {
// Build a POJO from the EJB entity returned by the finder.
return createPojo (result);
}
return result;
}
Most of the code in the method is involved with transforming Collection results into POJO’s.
To access the findById method I’d do:
return (TYPE) find ("findById", new Object[] { id } )
Getting the LocalHome interface is done by convention:
/** Get the local home appropriate to this mixin. */
protected Object getLocalHome () {
// Determine utility class name.
Class utilClass = findClass (getType() + "Util");
if (utilClass == null) {
throw new VRUtilityException ("ERROR: Could not look up utility class for type = '" + getType () + "' by convention.");
}
try {
return utilClass.getMethod ("getLocalHome", null).invoke (null, null);
} catch (Exception e) {
throw new VRUtilityException ("ERROR: Could isntantiate local home for class of type = '" + getType () + "' by convention using Method object.");
}
}
Because I know my Util class is #TYPE#Util I can rely on that by convention to get my utility class and instantiate a LocalHome to be used. (In my case the findClass() method looks for the #TYPE#Util class in one of three packages by convention. I could have search the classpath, but that seemed like overkill under the circumstances, when I know it’s in one of those three packages.)
Using the same recognition of patterns and convention allowed the replacement of boilerplate code in our persist method to.
Before:
public void persist ( Endowment endowment ) {
try {
// get the local home
EndowmentLocalHome endowmentLH = EndowmentUtil.getLocalHome ();
// create the entity
EndowmentLocal endowmentL = endowmentLH.create ();
// ensure that the foreign keys are set
setForeignKeys ( endowment );
// populate the entity
endowmentL.setEndowmentValue ( endowment );
// update the ID
endowment.setId( endowmentL.getId() );
} catch ( Exception e ) { throw new VRRemoteException ( e ); }
}
After:
public void persist ( Endowment endowment ) {
mixin.persist (endowment);
}
The reflection code that does it:
public void persist (Object bean) {
// Create an entity EJB bean using the localHome.
Object ejb = sendMessage ("create", getLocalHome (), null);
// Populate foreign ID's from associated POJO's.
setForeignKeys (bean);
// Populate the entity.
setValueOnEjb (bean, ejb);
// Get the id from the ejb.
String id = (String) sendMessage ("getId", ejb, null);
// Set the id on the bean (POJO).
sendMessage ("setId", bean, new Object[] { id });
}
The nice thing is I wrote the reflection version of the persist once and I can reuse it with one line of code. Bye bye boiler plate.
Conclusion
If you find yourself writing repetitive code, such as in my case when wrapping some API you want to abstract out, find the patterns and factor out that repetitive boilerplate code using reflection. You don’t need to waste your life writing repetitive code.
2 comments February 28, 2008
Follow me , style that matters for developers
Being a software developer are you following some standards and best practices that has to be followed?? Developing a software or writing small peice of code is just not the big deal. But what matters is , whether your written code make sence or does it adhere to the requirement. Coding is just one part , but there are othere things to follow where your code looks neat and clean . I am not talking about how to write code etc…. indeed i’m talking about how to make your code look clean and neat. There are some basic rules that every developer must adhere to and the disastrous outcomes that can follow if these rules are not followed. Some of the basic rules you might already know , but are you following ??
1. Add comments to your code : Everybody knows this, but somehow forgets to follow it. How many times have you “forgotten” to add comments? It is true that the comments do not literally contribute to the functionality of a program. But time and time again you return to the code that you wrote two weeks ago and, for the life of you, you cannot remember what it does! You are lucky if this uncommented code is actually yours. In those cases something may spark your memory. Unfortunately most of the time a third party can scan your code too. Well , i recommend to specify what exaclty your code does.
Example : bad way of coding
public File getFile(String path,String fileName) {
if(path == null && fileName == null) {
throw someException;
}
if(fileName.endswith(“exe”)) {
throw someException;
}
}
In the above code it does not tell about the path or fileName , anybody who navigates this
method will come to conclusion that , this method will check for validations and etc..And he has not idea about the path or fileName
Add comments to your code
/**
This method returns a file for the specified path and filename.The fileName takes the file name that ends with exe only and path should be fully qualified name .
@path refers to path Name , fully qualified
@fileName refers to file name with exe extention file name
@return file
*/
public File getFile(String path,String fileName) {
if(path == null && fileName == null) {
throw someException;
}
if(fileName.endswith(“exe”)) {
throw someException;
}
}
2. Say no to Print lines : Its obivious that many of the developers are tend to write sysouts everywhere in methods. But ofcourse its not a bad idea for debugging purpose .And we say to ourselves that we will delete these later. But we often forget to delete these lines of code or we do not want to delete them. polluting more sysouts in your code looks odd , but instead keep a common method which print your things.
3. Braces and Indentation: Indent style (cf., Raymond, “Indent Style”), or the placement of braces (“{” and “}”) and the associated indentation of code, is another of the religious issues related to writing code. There are several indent styles common to C-style languages like Java, and I am not going to suggest that one of them is superior. But following indentation your code look neat.
4. Blocks and Statements
->Put only one statement per line.
->Always use braces with control statements (e.g., ‘if’).
->Consider marking the end of a block with a comment (e.g., } // end if), particularly with long or nested blocks.
->Put variable declarations at the beginning of a block.
->Always initialize variables.
->If you want to be a perfectionist, left-align variable names.
->Indent the case clauses in a switch block.
->Put whitespace before and after operators.
->In if, for, or while, put whitespace before the “(“.
->Use whitespace and parentheses in expressions to increase readability.
5. Unit-test. Unit-test. Unit-test.
I am not going to go into any details as to what is the best way to unit-test your code. I am just going to say that that it must be done. This is the most basic rule of programming. This is one rule that, above all, cannot be omitted. It would be great if your fellow developer could create and execute a test plan for your code, but if that is not possible, you must do it yourself. When creating a unit test plan, follow these basic rules:
->Write the unit test before writing code for class it tests.
->Capture code comments in unit tests.
->Test all the public methods that perform an “interesting” function (that is, not getters and setters, unless they do their getting and setting in some unique way)
6. Always Prepare Document Requirements. Every business requirement must be documented. This could be true in some fairy tale, but it is far from that in the real world. No matter how time-pressed your development is, no matter how tight the deadlines, you must always make sure that every business requirement is documented.
Add comment January 18, 2008
Tuning Eclipse Performance and Avoiding OutOfMemoryExceptions
Combating OutOfMemoryExceptions
A majority of OutOfMemoryException s when using Eclipse are caused by too little heap space for your VM. In this case the old wisdom of adjusting your maximum heap space with something like -vmargs -Xmx256m is still good advice; giving your Java apps more space to run in always helps performance. However, there are situations where even with an enourmous heap size you can still end up with OutOfMemoryException s in your workbench. The reason for this is that your VM is not running out of heap space, but is instead running out of what is known as permSpace . The VM’s permSpace is the area of the VM that is used to store data structures and class information (not instances, but the class definitions themselves). In the case of a large enough Java application that may contain 10s of thousands of class files that must be loaded you start to see how the VM can physically run out of space storing all of that information into the default permSpace . If you have run into a situation where you have run out of permSpace you will want to adjust your Eclipse shortcut, eclipse.ini , or startup script to include the argument -XX:MaxPermSize=64m ; generally speaking the more memory you give the VM, the more performant it will be. Tuning this value can help you find what works best for your Eclipse install.
Improving Performance
Now let’s assume that you are not encountering any exceptions and Eclipse is running just fine, but you would like to improve the performance. I have found 2 rules of thumb when tweaking the heap size and permSize for Eclipse to maximize performance, and that is to 1) give the VM as much ram as you can spare and 2) set your min and max values to the same amounts to avoid resizing. While neither of these guidelines are revolutionary I have found using them both to really help improve performance; in the case of MyEclipse 4.0.3 on Eclipse 3.1 my subjective perception of the performance increase is anywhere from 50% to a 100% increase on my machine (your mileage may varry depending on hardware, current arguments, etc).
For a machine with 512MB of ram with the developer mainly using just Eclipse (any maybe a browser and IM) I would suggest the following arguments: -vmargs -Xms256m -Xmx256m -XX:PermSize=64m -XX:MaxPermSize=64m
For a machine with 1024MB of ram with the similar run case as described above I would suggest: -vmargs -Xms512m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=128m
and for machines with anymore ram than what I outlined above, adjust to fit your preferences. I have 4GB of ram in my machine and use a heap size of 1024m and a permSize of 512m. You may need to go through a few test runs with different settings to find which one works best for your computer. You may find that only using 256m heap space is sufficient while you end up needing to increase your permSize to 128m. I’ll leave it up to you to decide.
2 comments December 19, 2007
java.6 —–new I/O API’s for the needy
Free Diskspace:
One can now discover the amount of disk space left in the partition named by
the given file !!! This is a very
handy feature, for example, installers can now determine beforehand
how much diskspace is available on a partition that it’s going to install the stuff on.
Three new methods have been added to java.io.File class:
getFreeSpace()
getUsableSpace()
getTotalSpace()
Using these methods one can do something like:
import java.io.*;
:
:
:
File dir;
System.out.println(“Total MB Free Usable”);
System.out.format(” %6d %6d %6d\n”,
(dir.getTotalSpace() >> 20),
(dir.getFreeSpace() >> 20),
(dir.getUsableSpace() >> 20));
Changing File Attributes:
In java6 the java.io.File API provides access to the file attributes for changing its readability, ability to write and ability to make it executable. Check out the following methods for playing around with file attributes:
Changing readability: owner-only, owner or everybody
Making it writable or read-only: owner-only, owner or everybody
Making it executable or not executable: owner-only, owner or everybody
Add comment November 9, 2007
Make use of java.util.Scanner
Suppose if you want to accept an input from a Keybord ,in a basic application like public static void main() kind of programe you will need to import java.io.BufferdReader and io.InputStreamReader … you make long sentence like:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
This is something very hard snip….
one of the weird thing is , if you want to convert to integer type then you must parse it:
int num = Integer.parseInt(br.readLine());
and to convert , double , then,
double d = Double.parseDouble(br.readLine());
and code goes on….
this is two way process on every code , to accept and to convert; this really kills the time and performance…
One of the best way to manage, is to use the class called “Scanner” which is shiped in j2se5.0… found in java.util package.
This AIP is a simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods !!!
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in) String str = sc.next(); //read string int num = sc.nextInt(); // read integer long lnum = sc.nextLong(); // read long double d = sc.nextDouble(); // read double and more..... read javaDoc 5.0 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(br.readLine()); the above code just boils down to : Scanner sc = new Scanner(System.in) int num = sc.nextInt(); Scanner is very useful when you are using regular expression , searching patterns... String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close(); prints the output 1 2 red blue
3 comments October 8, 2007

