Sunday, 19 February 2012
Friday, 15 July 2011
Wednesday, 13 July 2011
Saturday, 2 July 2011
Notepad
Notepad
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.io.*;
public class Editor extends Frame
{
String filename;
TextArea tx;
Clipboard clip = getToolkit().getSystemClipboard();
Editor()
{
setLayout(new GridLayout(1,1));
tx = new TextArea();
add(tx);
MenuBar mb = new MenuBar();
Menu F = new Menu("file");
MenuItem n = new MenuItem("New");
MenuItem o = new MenuItem("Open");
MenuItem s = new MenuItem("Save");
MenuItem e = new MenuItem("Exit");
n.addActionListener(new New());
F.add(n);
o.addActionListener(new Open());
F.add(o);
s.addActionListener(new Save());
F.add(s);
e.addActionListener(new Exit());
F.add(e);
mb.add(F);
Menu E = new Menu("Edit");
MenuItem cut = new MenuItem("Cut");
MenuItem copy = new MenuItem("Copy");
MenuItem paste = new MenuItem("Paste");
cut.addActionListener(new Cut());
E.add(cut);
copy.addActionListener(new Copy());
E.add(copy);
paste.addActionListener(new Paste());
E.add(paste);
mb.add(E);
setMenuBar(mb);
mylistener mylist = new mylistener();
addWindowListener(mylist);
}
class mylistener extends WindowAdapter
{
public void windowClosing (WindowEvent e)
{
System.exit(0);
}
}
class New implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
tx.setText(" ");
setTitle(filename);
}
}
class Open implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
FileDialog fd = new FileDialog(Editor.this, "select File",FileDialog.LOAD);
fd.show();
if (fd.getFile()!=null)
{
filename = fd.getDirectory() + fd.getFile();
setTitle(filename);
ReadFile();
}
tx.requestFocus();
}
}
class Save implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
FileDialog fd = new FileDialog(Editor.this,"Save File",FileDialog.SAVE);
fd.show();
if (fd.getFile()!=null)
{
filename = fd.getDirectory() + fd.getFile();
setTitle(filename);
try
{
DataOutputStream d = new DataOutputStream(new FileOutputStream(filename));
String line = tx.getText();
BufferedReader br = new BufferedReader(new StringReader(line));
while((line = br.readLine())!=null)
{
d.writeBytes(line + "\r\n");
d.close();
}
}
catch(Exception ex)
{
System.out.println("File not found");
}
tx.requestFocus();
}
}
}
class Exit implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
void ReadFile()
{
BufferedReader d;
StringBuffer sb = new StringBuffer();
try
{
d = new BufferedReader(new FileReader(filename));
String line;
while((line=d.readLine())!=null)
sb.append(line + "\n");
tx.setText(sb.toString());
d.close();
}
catch(FileNotFoundException fe)
{
System.out.println("File not Found");
}
catch(IOException ioe){}
}
class Cut implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String sel = tx.getSelectedText();
StringSelection ss = new StringSelection(sel);
clip.setContents(ss,ss);
tx.replaceRange(" ",tx.getSelectionStart(),tx.getSelectionEnd());
}
}
class Copy implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String sel = tx.getSelectedText();
StringSelection clipString = new StringSelection(sel);
clip.setContents(clipString,clipString);
}
}
class Paste implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Transferable cliptran = clip.getContents(Editor.this);
try
{
String sel = (String) cliptran.getTransferData(DataFlavor.stringFlavor);
tx.replaceRange(sel,tx.getSelectionStart(),tx.getSelectionEnd());
}
catch(Exception exc)
{
System.out.println("not string flavour");
}
}
}
public static void main(String args[])
{
Frame f = new Editor();
f.setSize(500,400);
f.setVisible(true);
f.show();
}
}
NegativeLength Exception
NegativeLength Exception
import java.io.*;
public class NegativeLengthException extends Exception {
/** Test NegativeLengthException */
public static void main(String[] args) {
try {
int lineLength = readLength();
for(int i=0; i System.out.print("*");
}
System.out.println();
} catch (NegativeLengthException nle) {
System.out.println("NegativeLengthException: " +
nle.getMessage());
}
}
public NegativeLengthException() {
super("Negative dimensions not permitted.");
}
public NegativeLengthException(String message) {
super(message);
}
// readLength catches IOExceptions locally but lets the
// calling method handle NegativeLengthExceptions.
private static int readLength() throws NegativeLengthException {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("Enter length: ");
System.out.flush();
int len = 0;
try {
String line = in.readLine();
len = Integer.parseInt(line);
if (len < 0) {
throw new NegativeLengthException();
}
} catch (IOException ioe) {
System.out.println("Problem reading from keyboard");
}
return(len);
}
}
Moving a File or Directory to Another Directory
Moving a File or Directory to Another Directory
public static void main(String args[]){
try{
// File (or directory) to be moved
File file = new File("file.txt");
// Destination directory
File dir = new File("gg");
// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
System.out.println("File moved");
}
}
catch (Exception ioe){
ioe.printStackTrace();
}
}
Method Overriding
Method Overriding
class A {
String name() { return "A"; }
}
class B extends A {
String name() { return "B"; }
}
class C extends A {
String name() { return "C"; }
}
public class Overriding {
public static void main(String[] args) {
A[] tests = new A[] { new A(), new B(), new C() };
for (int i = 0; i < tests.length; i++)
System.out.print(tests[i].name());
}
}
Method Overloading
Method Overloading
import java.awt.Container;
import javax.swing.*;
public class MethodOverload extends JApplet
{
JTextArea outputArea;
public void init()
{
outputArea = new JTextArea( 2, 20 );
Container c = getContentPane();
c.add( outputArea );
outputArea.setText(
"The square of integer 7 is " + square( 7 ) +
"\nThe square of double 7.5 is " + square( 7.5 ) );
}
public int square( int x )
{
return x * x;
}
public double square( double y )
{
return y * y;
}
}
Making the application wait for some given time
Making the application wait for some given time
import java.util.*;
public class WaitForSomeTime
{
public static void main(String args[])
{
WaitForSomeTime waitForSomeTime = new WaitForSomeTime();
waitForSomeTime.myMethod();
}
public void myMethod()
{
System.out.println("Starting......");
// pause for a while
Thread thisThread = Thread.currentThread();
try
{
thisThread.sleep(10000);
}
catch (Throwable t)
{
throw new OutOfMemoryError("An Error has occured");
}
System.out.println("Ending......");
}
}
Friday, 1 July 2011
Listing the Files or Subdirectories in a Directory
Listing the Files or Subdirectories in a Directory
public static void main(String args[]){
try{
File dir = new File("d:\\temp");
String[] children = dir.list();
if (children == null) {
System.out.println("Directory does not exist or is not a Directory");
} else {
for (int i=0; i // Get filename of file or directory
String filename = children[i];
System.out.println(filename);
}
}
// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
};
children = dir.list(filter);
// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
}
catch (Exception ioe){
ioe.printStackTrace();
}
}
Listing the File System Roots
Listing the File System Roots
public static void main(String args[]){
try{
File[] roots = File.listRoots();
for (int i=0; i System.out.println((roots[i]));
}
}
catch (Exception ioe){
ioe.printStackTrace();
}
}
Listing All Available Unicode to Character Set Converters
Listing All Available Unicode to Character Set Converters
public static void main(String args[])
{
Map map = Charset.availableCharsets();
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
// Get charset name
String charsetName = (String)it.next();
System.out.println("Charset Name "+charsetName);
// Get charset
Charset charset = Charset.forName(charsetName);
System.out.println("Charset "+charset);
}
}
List of users in the network
List of users in the network
import java.io.*;
public class NetworkUsers
{
public static void main(java.lang.String[] args)
{
StringBuffer strBuffer= new StringBuffer();
String line= null;
try
{
Process process= Runtime.getRuntime().exec("cmd");
BufferedReader b=
new BufferedReader(new InputStreamReader(process.getInputStream()));
PrintWriter to= new PrintWriter(process.getOutputStream());
to.println("net view");
to.println("exit");
to.close();
try
{
// we need the process to end, else we'll get an
// illegal Thread State Exception
line= b.readLine();
while (line != null)
{
strBuffer.append(line+"
");
line= b.readLine();
}
process.waitFor();
}
catch (InterruptedException inte)
{
System.out.println("InterruptedException Caught");
}
if (process.exitValue() == 0)
{
System.out.println(strBuffer.toString());
}
process.destroy();
}
catch (IOException ioe)
{
System.out.println(
"IO Exception Occured While Messing aruond with Processes! -> " + ioe);
}
}
}
List all '.java' files present in a directory.
List all '.java' files present in a directory.
import java.io.*;
public class FileExt
{
public static void main(String args[])
{
try
{
String[] filesList;
File dir = new File(".");
filesList= dir.list(new FileFilter());
for (int i=0;i {
System.out.println(filesList[i]);
}
}
catch(Exception e){}
}
}
class FileFilter implements FilenameFilter
{
public boolean accept(File dir, String name)
{
return (name.endsWith(".java"));
}
}
Linear Search of an Array
Linear Search of an Array
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LinearSearch extends JApplet implements ActionListener
{
JLabel enterLabel, resultLabel;
JTextField enter, result;
int a[];
public void init()
{
Container c = getContentPane();
c.setLayout( new FlowLayout() );
enterLabel = new JLabel( "Enter integer search key" );
c.add( enterLabel );
enter = new JTextField( 10 );
enter.addActionListener( this );
c.add( enter );
resultLabel = new JLabel( "Result" );
c.add( resultLabel );
result = new JTextField( 20 );
result.setEditable( false );
c.add( result );
// create array and populate with even integers 0 to 198
a = new int[ 100 ];
for ( int i = 0; i < a.length; i++ )
a[ i ] = 2 * i;
}
// Search "array" for the specified "key" value
public int linearSearch( int array[], int key )
{
for ( int n = 0; n < a.length; n++ )
if ( array[ n ] == key )
return n;
return -1;
}
public void actionPerformed( ActionEvent e )
{
String searchKey = e.getActionCommand();
// Array a is passed to linearSearch even though it
// is an instance variable. Normally an array will
// be passed to a method for searching.
int element = linearSearch( a, Integer.parseInt( searchKey ) );
if ( element != -1 )
result.setText( "Found value in element " + element );
else
result.setText( "Value not found" );
}
}
Java Script Trim() function
Java Script Trim() function
function fnTrim() {
for(var L=0; L if(this.charAt(L)!=" ")break;
for(R=this.length-1; R>=0;R--)
if(this.charAt(R)!=" ")break;
if(L==this.length)return "";
return this.substring(L,R+1);
}
String.prototype.trim=fnTrim;
//**** For trim the crtl
if ((document.frm.crtlName.value).trim()=="") {
//*** Here ur code
}
Information Servlet
Information Servlet
// Import standard networking I/O packages
import java.net.*;
import java.io.*;
// Enumeration from util
import java.util.Enumeration;
// Import servlet packages
import javax.servlet.*;
import javax.servlet.http.*;
//
//
// InfoServlet
//
//
public class InfoServlet extends HttpServlet
{
// Get method of servlet
public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException
{
// Define content type
response.setContentType("text/html");
// Get information about client and server
String clientBrowser = request.getHeader("User-Agent");
String clientReferer = request.getHeader("Referer");
String clientIP = request.getRemoteAddr();
String serverOS = System.getProperty("os.name");
String serverOSVersion = System.getProperty("os.version");
String serverOSArch = System.getProperty("os.arch");
// Get a servlet output stream for the response
ServletOutputStream sout = response.getOutputStream();
// Print header information
sout.println ("<HTML><HEAD><TITLE>InfoServlet Response</TITLE></HEAD>");
// Print body information
sout.println ("<BODY BGCOLOR='white' COLOR='black'>");
sout.println ("<H2>InfoServlet</H2><HR>");
// Print information about client
sout.println ("<H3>Client :-</H3>");
// Check for presence of user-agent header field
if (clientBrowser != null)
sout.println ("User-Agent : " + clientBrowser + "<BR>");
// Print IP address
sout.println ("IP Address : " + clientIP + "<BR>");
// Check for presence of referer header field
if (clientReferer != null)
sout.println ("Last page : " + clientReferer + "<BR>");
// Print information about server
sout.println ("<H3>Server</H3>");
// Check to see if each property is valid, and if so, output it
if ( (serverOS != null) & (serverOSVersion != null) )
sout.println ("Server O/S : " + serverOS + " v" + serverOSVersion + "<BR>");
if ( serverOSArch != null)
sout.println ("Server CPU : " + serverOSArch + "<BR>");
// Obtain a reference to the server context
ServletContext context = getServletContext();
if (context != null)
{
// Display information about servlets
sout.println ("<h3> Servlet information </h3>");
// Table for servlet info
sout.println ("<table border='1' width=70%>");
sout.println ("<tr><td><b>Servlet Name</b></td></tr>");
for (Enumeration e = context.getServletNames(); e.hasMoreElements();)
{
// Get name of servlet
String name = (String) e.nextElement();
sout.println ("<tr> <td>");
sout.println (name);
sout.println ("</td> </tr>");
}
sout.println ("</table>");
}
else
sout.println ("Could not determine servlet context");
// Write footer information
sout.println ("</BODY></HTML>");
// Flush
sout.flush();
}
// Post method of servlet
public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException
{
// Perform same action as get method
doGet(request, response);
}
public String getServletInfo()
{
return new String (
"InfoServlet - reports information on client connection and server state"
);
}
}
Histogram printing program
Histogram printing program
import javax.swing.*;
public class Histogram
{
public static void main( String args[] )
{
int n[] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
String output = "";
output += "Element\tValue\tHistogram";
for ( int i = 0; i < n.length; i++ )
{
output += "\n" + i + "\t" + n[ i ] + "\t";
for ( int j = 1; j <= n[ i ]; j++ ) // print a bar
output += "*";
}
JTextArea outputArea = new JTextArea( 11, 30 );
outputArea.setText( output );
JOptionPane.showMessageDialog( null, outputArea,"Histogram Printing Program",JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
}
}
Getting and Setting the Modification Time of a File or Directory
Getting and Setting the Modification Time of a File or Directory
public static void main(String args[]){
try{
File file = new File("file.txt");
// Get the last modified time
long modifiedTime = file.lastModified();
// 0L is returned if the file does not exist
// Set the last modified time
long newModifiedTime = System.currentTimeMillis();
boolean success = file.setLastModified(newModifiedTime);
if (!success) {
System.out.println("Operation failed");
}
}
catch (Exception ioe){
ioe.printStackTrace();
}
}
Get hashtable keys from value
Get hashtable keys from value
class keyhash
{
ResultSet rs;
Hashtable hash;
Vector v;
static int i;
Enumeration e;
public static void main(String[] args)
{
keyhash gs = new keyhash();
System.out.println("Hello World!");
gs.getresultset();
}
public void getresultset()
{
Hashtable hash = new Hashtable();
Vector v = new Vector();
boolean connected = dbConnect();
// Establish database connection here
if(connected == true)
{
try{
PreparedStatement getArticles = db.con.prepareStatement
("select * from xx where id = ?"
// sample query
)
String artid;
getArticles.setInt(1, 4);
//This passes integer 4 as a parameter in
//the sql query
rs = getArticles.executeQuery();
while (rs.next() == true)
{
key = rs.getString(1);
value = rs.getString(2);
hash.put(key,value);
//Hashtable populated
}
fillvector(hash,v);
getkeys(v);
rs.close();
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
public void fillvector(Hashtable hash,Vector v)
{
int j=0;
boolean success;
Enumeration e = hash.keys();
while(e.hasMoreElements())
{
String key = (String)(e.nextElement());
String value = (String)hash.get(key);
if(value.matches("*****"))
//Put the value here to retrieve the
// corresponding keys
{
v.addElement(key);
//Add the corresponding keys to the vector
}
}
}
public void getkeys(Vector v)
{
Enumeration ev= v.elements();
while (ev.hasMoreElements())
{
System.out.println(ev.nextElement());
// Print the keys related to a single value
}
}
}
Subscribe to:
Posts (Atom)