Class to DataInputStream

Im trying to convert Class object that I get from findSystemClass() in ClassLoader into a DataInputStream object, is there any way of doing that. Secondary is there any way to convert THIS Class into a .class file in current directory
Thanks

Hi
This is part of my class loader , I want to convert all there Class that findSystemClass() returns to DataInputStream or dump. In my program result is Class object which gets Class returned by findSystemClass(). I want to convert this into DataInputStream
public synchronized Class loadClass(String className, boolean resolveIt)
throws ClassNotFoundException {
Class result;
byte classData[];
JavaClass java_class;
System.out.println(" >>>>>> Load class : "+className);
/* Check our local cache of classes */
result = (Class)classes.get(className);
if (result != null) {
System.out.println(" >>>>>> returning cached result.");
return result;
/* Check with the primordial class loader */
try {
// result = super.findSystemClass(className);
// >> I WANT TO CONVERT THIS result TO JavaClass <<<<
Im not sure result can be written as result.getClass() as adviced by you.
Thanks for help , I really appreciate it.

Similar Messages

  • Externalizable vs DataOutputStream/DataInputStream (Storable Interface)

    I have created an interface Storable as below which I use to save a complex Object to a byte array and ultimately to a database. The total processing time is 1hour and 5 minutes.
    public interface Storable
         void readData(DataInputStream in) throws IOException;
         void writeData(DataOutputStream out) throws IOException;
    I then swapped to Externalizable.
    I changed the top Object readData/writeData functions to
    readExternal and writeExternal.
    Then I added new readData/writeData functions to the contained Objects
    as below - so these objects are "new"ed and filled in by my code.
    void readData(InputObject in) throws IOException;
    void writeData(OutputObject out) throws IOException;
    Total processing time was reduced to 33minutes.
    Can anybody explain this >50% speed improvement?
    Also I would rather not use Externalizable so I can decouple the persisted data away from the Java code but it looks like one heck of a time penalty for doing so.

    The point is the only difference between the code I have written is that one is using
    ObjectInput/ObjectOutput (Externalizable) (34 minutes)
    the other is using
    DataOutputStream/DataInputStream (Storable) (1hour 5 minutes)
    and my code for the 2 methods is basically the same.
    This would lead to the conclusion that one of or both Java classes DataOutputStream/DataInputStream are very inefficient and I want to know why?

  • If object is send twice BUT CHANGED server doesn't respond properly

    It seams there is a bug in Java 6 Serialization:
    Instantiate object x.
    Send it to the server and check the values.
    Change your client-side instance.
    Resend and check the values again.
    The server still shows the old values.
    To prove this is wrote a little code example:
    package testserializablebug;
    import java.io.Serializable;
    public class SharedObject implements Serializable {
        private String s;
        private int i;
        public SharedObject(String s, int i) {
            this.s = s;
            this.i = i;
        public void setI(int i) {
            this.i = i;
        @Override
        public String toString() {
            return s + "::" + i;
    package testserializablebug;
    import java.io.*;
    import java.net.*;
    public class ClientTest {
        DataInputStream in;
        ObjectOutputStream outO;
        public ClientTest() throws UnknownHostException, IOException {
            Socket socket = new Socket("localhost", 8000);
            in = new DataInputStream(socket.getInputStream());
            outO = new ObjectOutputStream(socket.getOutputStream());
            SharedObject so = new SharedObject("Text", 3);
            compareResponse(so);
            so.setI(5);
            compareResponse(so);
        private void compareResponse(SharedObject so) throws IOException {
            outO.writeObject(so);
            String actual = in.readUTF();
            String expected = so.toString();
            if (!actual.equals(expected)) {
                System.err.println("actual    " + actual);
                System.err.println("expected  " + expected);
            } else {
                System.out.println("OK        " + actual);
        public static void main(String[] args) throws UnknownHostException, IOException {
            new ClientTest();
    package testserializablebug;
    import java.io.*;
    import java.net.*;
    public class ServerTest {
        public static void main(String[] args) throws IOException, ClassNotFoundException {
            Socket socket = new ServerSocket(8000).accept();
            ObjectInputStream inO = new ObjectInputStream(socket.getInputStream());
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            SharedObject so1 = (SharedObject) inO.readObject();
            out.writeUTF(so1.toString());
            SharedObject so2 = (SharedObject) inO.readObject();
            out.writeUTF(so2.toString());
    }Is this a bug, or am doing something wrong? Any ideas how i can bypass this bug (if it is)?

    Is this a bug, or am doing something wrong? Any ideas how i can bypass this bug (if it is)?It isn't a bug. Read the javadoc for ObjectOutputStream, and for the reset method.
    Kaj

  • Problem using sockets, etc.

    Alrighty, well I'm building a very basic chat server using the tutorial from IBM, and when I got to compile it, I get the following (DOS capture):
    Server.java:51: warning: [unchecked] unchecked call to put(K,V) as a member of t
    he raw type java.util.Hashtable
    outputStreams.put(s, dout);
    ^
    .\ServerThread.java:27: cannot find symbol
    symbol : class DataIntputStream
    location: class ServerThread
    DataInputStream din = new DataIntputStream(socket.getInputStream());
    ^
    1 error
    1 warning
    Not sure what the first one means, and I'm none too sure how to correct the second one. Suggestions?

    It is a warning you'll get from java 5 and up when you use plain Object types where you would need to use a generic type. Look up "generics" for a more detailed explanation.

  • Muticlient chat

    i tried to write a multiple client chat using thread and its not working
    plz help me out
    here is the server code
    import java.net.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class myServer {
           DataInputStream in;
             DataOutputStream out;
             ServerSocket server;
             Socket socket;
            String name,clientname;     
            acceptclient a[]=new acceptclient[5];
        public static void main(String []args) {
             try{
             myServer s=new myServer();
             s.socketstaff();
             catch(Exception e){
                  System.out.println("error");
        public void socketstaff(){
             try{
             server =new ServerSocket(8000);
             int i=0;
             while(true){
                  socket=server.accept();
                   a=new acceptclient(socket);
         Thread t=new Thread(a[i]);
         i++;
              t.start();
         catch(Exception e){
                   System.out.println(e);
                   //System.out.println(e.printStackTrace());
    public acceptclient[] getallclient(){
         return a;
    class acceptclient implements Runnable{
         Socket socket;
         DataInputStream in;
    DataOutputStream out;
    String name,clientname;
    String text;
    acceptclient ac[];
    myServer ms=new myServer();
         public acceptclient(Socket socket){
              this.socket=socket;
         public void run(){
              try{
                   in = new DataInputStream(socket.getInputStream());
                   out = new DataOutputStream(socket.getOutputStream());
                   while(true){
                   text=in.readUTF();
                   writetoall(text);
              }catch(Exception e){
                   System.out.println(e+"error here");
         public Socket getSocket(){
              return socket;
         //send data to all clients
         public void writetoall(String sendtext){
              //error is in here, i guess problem is in object
              ac=ms.getallclient();
              for(int i=0;i<5;i++){
                   try{
                        new DataOutputStream( ac[i].getSocket().getOutputStream() ).writeUTF(sendtext); //this line can be the mistake
                   }catch(Exception e){
                        System.out.println(e+" error there");
    i get an exception java.lang.NullPointerException error there
    java.lang.NullPointerException error there
    java.lang.NullPointerException error there
    java.lang.NullPointerException error there
    java.lang.NullPointerException error there
    the problem is due to improper object creation in the writetoall() function (Probably). Please help
    THanks in Advance                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    i have initialized the value text but still no use, i have made little modification to the code
    import java.net.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class myServer {
           DataInputStream in;
             DataOutputStream out;
             ServerSocket server;
             Socket socket;
            String name,clientname;     
            acceptclient a[]=new acceptclient[5];
        public static void main(String []args) {
             try{
             myServer s=new myServer();
             s.socketstaff();
             catch(Exception e){
                  System.out.println("error");
        public void socketstaff(){
             try{
             server =new ServerSocket(8000);
             int i=0;
             while(true){
                  socket=server.accept();
                   a=new acceptclient(socket,i);
         Thread t=new Thread(a[i]);
              t.start();
              i++;
         catch(Exception e){
                   System.out.println(e);
    public acceptclient[] getallclient(){
         return a;
    class acceptclient implements Runnable{
         Socket socket;
         DataInputStream in;
    DataOutputStream out;
    String name,clientname;
    String text="";
    acceptclient ac[]=new acceptclient[5];
    int number=0;
    myServer ms=new myServer();
         public acceptclient(Socket socket, int numb){
              this.socket=socket;
              this.number=numb;
         public int getNumber(){
              return number;
         public void run(){
              try{
                   in = new DataInputStream(socket.getInputStream());
                   out = new DataOutputStream(socket.getOutputStream());
                   while(true){
                   text=in.readUTF();
                   writetoall(text);
              }catch(Exception e){
                   System.out.println(e+"error here");
         public Socket getSocket(){
              return socket;
         //send data to all clients
         public void writetoall(String sendtext){
              try{
              //i guess problem is in object
                   ac=ms.getallclient();
                   for(int i=0;i<5;i++){
                        System.out.println("this "+ ac[i].getNumber()); //exception pointed in this line
                             new DataOutputStream( ac[i].getSocket().getOutputStream() ).writeUTF(sendtext); //this line can be the mistake
              }catch(Exception e){
                        e.printStackTrace(System.out);
    java.lang.NullPointerException
    at acceptclient.writetoall(myServer.java:125)
    at acceptclient.run(myServer.java:102)
    at java.lang.Thread.run(Thread.java:619)
    System.out.println("this "+ ac.getNumber()); exception is shown for this line

  • Strange server

    I have write a java server on socket connection. a cell connect to it. when I use the simulator and I brutally close it the server say "cliend down" but when I use a really phone and I switch it off the server don't stop and continue to send. Why?
    I catch the exception...
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.ArrayList;
    public class TCPServer 
         DataInputStream is;
         DataOutputStream os;
         boolean flag_ricezione=true;
         ArrayList collezione_socket;
        public void start()
         int port=6969;
         int backlog=50;
         InetAddress bindAddr;
         collezione_socket=new ArrayList();
          try
           bindAddr = InetAddress.getLocalHost();
          } catch (UnknownHostException e2)
           {e2.printStackTrace();
            System.out.println("Errore nel binding, esco.");
            return;
          ServerSocket serverSocket=null;
           try
           serverSocket = new ServerSocket(port,backlog, bindAddr);
           } catch (IOException e)
           {e.printStackTrace();
            System.out.println("Eccezione apertura Socket. Esco.");
            return;
           //Informazioni sul Server in ascolto
           InetAddress indirizzo = serverSocket.getInetAddress();
           String server = indirizzo.getHostAddress();
          int porta_s = serverSocket.getLocalPort();
          System.out.println("In ascolto Server: "+ server + " porta: " + porta_s);
          //Ciclo infinito per ascolto dei Client
          while (true)
           System.out.println("In attesa di chiamate dai Client... ");
           Socket socket=new Socket();
           try
             System.out.println("Qualcuno cerca di connettersi.");
             socket = serverSocket.accept();
             collezione_socket.add(socket);
             Receive r=new Receive (socket,this);
             r.start();                         
           } catch (IOException e)
             {//e.printStackTrace();
              System.out.println("Errore nell'apertura di una socket.");
         try
          Thread.sleep(5000);
          } catch (InterruptedException e)
           {//e.printStackTrace();
              System.out.println("C'e' stato un errore nel periodo di attesa prima di una nuova connessione.");     
        public void removeSocket(Socket s)
         collezione_socket.remove(s);     
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.Socket;
    public class Receive extends Thread implements Runnable{
         private Socket s;
         private DataInputStream is;
         private DataOutputStream os;
         private TCPServer parent;
         boolean flag_ricezione=true;
         public Receive(Socket S, TCPServer T)
          this.s=S;
          this.parent=T;
         public void run()
          //Informazioni sul Client che ha effettuato la chiamata
         InetAddress address = s.getInetAddress();
         String client = address.getHostName();
         int porta_c = s.getPort();
         System.out.println("Il client: " + client + " porta: " + porta_c+ " si e' connesso.");
         //Stream di byte utilizzato per la comunicazione via socket
         try
           is = new DataInputStream(s.getInputStream());
           os = new DataOutputStream(s.getOutputStream());
         } catch (IOException e1)
          {//e1.printStackTrace();
          System.out.println("Eccezione Input Output stream.");
          chiudi();
          return;
          String userInput=null;
          while(flag_ricezione)
          char ch = 0;           
          StringBuffer b = new StringBuffer();               
          System.out.println("Aspetto il nome del client");
          System.out.println("Sto per ricevere qualcosa dal client.");
          try
            while((ch = is.readChar()) != '\n')
            {b.append(ch);}
           }catch (IOException e)
            {//e.printStackTrace();
             System.out.println("Errore nella ricezione.Chiudo.");
             chiudi();
             return;
           userInput =b.toString();
          System.out.println("Il Client "+client+" ha scritto: " + userInput);
          if(userInput.compareTo("kill")!=0)
            Send s=new Send(userInput,os,"path del file dove leggere",this);
           s.start();//lancia invio
          else
          {System.out.println("Chiusura connessione ricevuta.Chiudo.");
            chiudi();
            return;
         public void chiudi()
              flag_ricezione=false;
             try
               os.close();
               is.close();
              s.close();
             } catch (IOException e)
              {//e.printStackTrace();
                  System.out.println("Errore nella chiusura input e output stream.");
             parent.removeSocket(s);
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.SocketException;
    public class Send extends Thread implements Runnable{
         private String user;
         private DataOutputStream os;
         private String path;
         private Receive parent;
         private boolean flag_spedizione;
         public Send(String USER, DataOutputStream OS, String PATH, Receive Parent)
          this.user=USER;
          this.os=OS;
          this.path=PATH;
          this.parent=Parent;
          flag_spedizione=true;     
         public void run()
         String message="Ciao ti risp.";
         while (flag_spedizione)
          try
           for (int i=0;i<message.length();i++)
              {os.writeChar(message.charAt(i));}
           os.writeChar('\n');
           //os.flush();
              System.out.println("Risposto al client");
          } catch (SocketException s)
           {//s.printStackTrace();
            System.out.println("Errore nella spedizione.");
            chiudi();     
            return;
           catch (IOException e)
           {//e.printStackTrace();
            System.out.println("Errore nella spedizione.");
            chiudi();
            return;
          try
           Thread.sleep(5000);
          } catch (InterruptedException e)
            {//e.printStackTrace();
              System.out.println("Eccezione sleep. chiudo thread.");
              chiudi();
              return;
         System.out.println("Smetto di spedire.");
         chiudi();
         return;   
         public void chiudi()
          flag_spedizione=false;     
          try
           os.close();
          } catch (IOException e)
           {//     e.printStackTrace();
            System.out.println("Errore in chiusura output");
            return;
    }

    Hi AGrandDayOut-
    Are you sure that isn't the MAC address?
    It could be the mac address of any device on the network.
    Luck-
    -DaddyPaycheck

  • Need help in using Runtime class

    Hi all,
    I am facing problem with JRE versions of websphere and SUN JRE. Let me explain my problem.
    We have an application working fine in websphere, Now my organization wants to migrate this app to websphere. This application downloads some set of jar files to the client side when the user hits the server with some url. These jar files starts th swing based application in the client side , at the same it will try to communicate with EJB's deployed in the server(Now websphere) to get the data for menus and trees in the swing application. Because of different JRE in the websphere commucation problems like class cast exception are happening. Now we are downloading the the Websphere JRE to the client side and trying to start the application with the downloaded JRE(Even it is not required in case of weblogic in the exiting application also they are downloading the sun JRE). Here the problem starts for me. The execute method of Process class is not able to detect the main class. The waitFor method is returning non zero value. Here is my method.
    Can anybody guess what's wrong going on with this code.
    public Process spawnProcess(String szSpawnCommand) throws
    Exception
              szSpawnCommand = "C:\\ccc\\JRE\\bin\\javaw.exe com.att.suite.client.SuiteAppManager";
              System.out.println("starting processs "+szSpawnCommand);
    Process oProcess = null;
    try
    // oProcess = Runtime.getRuntime().exec(szSpawnCommand);
         Runtime rt = Runtime.getRuntime();
         System.out.println("Got runtime.....");
         oProcess = rt.exec("c:/ccc/JRE/bin/java com.att.suite.client.SuiteAppManager");
         //oProcess.waitFor();
    //oProcess = rt.exec("c:/ccc/JRE/bin/javaw -version");
    catch (Exception ex)
    // Throw an exception with the reason why the process
    // couldn't be spawned
    // The original message here confused end users - almost always
    // occurs due to lack of memory and we cannot determine actual
    // reason OS failed to spawn a process.
    // Changed to correct LCR MR#: 437
    // throw new Exception("Unable to spawn process with command: \"" +
    // szSpawnCommand + "\".\nSystem Reason: " + ex.getMessage());
    /*throw new Exception("You have insufficient memory to " +
    "launch this program. \nPlease quit some other " +
    "applications and try again.");*/
         System.out.println("In oProcess.... ");
    ex.printStackTrace();
    // Wait for a second to give the new process a chance
    // to run properly
    try
    Thread.sleep(1000);
    catch (Exception ex)
    final DataInputStream oProcStdOutStream = new DataInputStream(
    oProcess.getInputStream());
    final DataInputStream oProcStdErrStream = new DataInputStream(
    oProcess.getErrorStream());
    Thread oProcStdOutStreamThread = new Thread()
    public void run()
    try
    String szLine = null;
    while ((szLine = oProcStdOutStream.readLine()) != null)
    System.out.println("[FromProc1] " + szLine);
    catch (Exception ex)
         System.out.println("In oProcStdOutStream");
    ex.printStackTrace();
    oProcStdOutStreamThread.start();
    Thread oProcStdErrStreamThread = new Thread()
    public void run()
    try
    String szLine;
    while ((szLine = oProcStdErrStream.readLine()) != null)
    System.out.println("[FromProc2] " + szLine);
    catch (Exception ex)
    ex.printStackTrace();
    oProcStdErrStreamThread.start();
    // See if the process is still running properly
    int nProcessExitValue = 0;
    try
    nProcessExitValue = oProcess.exitValue();
         // nProcessExitValue = oProcess.waitFor();
         System.out.println("nProcessExitValue : "+nProcessExitValue);
    catch (Exception ex)
    // This means that the process is still running which
    // we'll consider a good sign.
    nProcessExitValue = 0;
    System.out.println("In nProcessExitValue");
    ex.printStackTrace();
    // Check the process exit value
    if (nProcessExitValue != 0)
    // Throw an exception with the return value of the spawned
    // process.
    // The original message here confused end users - almost always
    // occurs due to lack of memory and we cannot determine actual
    // reason OS failed to spawn a process.
    // Changed to correct LCR MR#: 437
    // throw new Exception("Unable to spawn process with command: \"" +
    // szSpawnCommand + "\".\nProcess Exit Value: " +
    // nProcessExitValue);
    throw new Exception("You have insufficient memory to " +
    "launch this program. \nPlease quit some other " +
    "applications and try again.");
         //System.out.println("In nProcessExitValue!=0");
    Here is the error :
    starting processs C:\ccc\JRE\bin\javaw.exe com.att.suite.client.SuiteAppManager
    Class loaded...
    Got runtime.....
    nProcessExitValue : 1
    [FromProc2] The java class is not found: com/att/launch/jre/Sample
    java.lang.Exception: You have insufficient memory to launch this program.
    Please quit some other applications and try again.
         at com.att.launch.jre.LaunchApp.spawnProcess(LaunchApp.java:525)
         at com.att.launch.jre.LaunchApp.spawnCJAS(LaunchApp.java:366)
         at com.att.launch.jre.LaunchApp.main(LaunchApp.java:171)
    Please help me, I am struggling with this problem from the long time. Or can any body suggest different way to solve this problem instead of downloading the JRE to the client side.
    Bhaskar

    Hi ,
    I am facing problem with JRE versions of websphere and SUN JRE. Let me explain my problem.
    We have an application working fine in websphere, Now my organization wants to migrate this app to websphere. This application downloads some set of jar files to the client side when the user hits the server with some url. These jar files starts th swing based application in the client side , at the same it will try to communicate with EJB's deployed in the server(Now websphere) to get the data for menus and trees in the swing application. Because of different JRE in the websphere commucation problems like class cast exception are happening.
         Now we are downloading the the Websphere JRE to the client side and trying to start the application with the downloaded JRE(Even it is not required in case of weblogic in the exiting application also they are downloading the sun JRE).
    Here the problem starts for me. The execute method of Process class is not able to detect the main class. The waitFor method is returning non zero value. Here is my method.
    Can anybody guess what's wrong going on with this code
    public Process spawnProcess(String szSpawnCommand) throws
    Exception
              System.out.println("starting processs "+szSpawnCommand);
    Process oProcess = null;
    try
         Runtime rt = Runtime.getRuntime();
         System.out.println("Got runtime.....");
         oProcess = rt.exec("c:/ccc/JRE/bin/java com.att.suite.client.SuiteAppManager");
    catch (Exception ex)
    throw new Exception("You have insufficient memory to " +
    "launch this program. \nPlease quit some other " +
    "applications and try again.");      
    // Wait for a second to give the new process a chance
    // to run properly
    try
    Thread.sleep(1000);
    catch (Exception ex)
    final DataInputStream oProcStdOutStream = new DataInputStream(oProcess.getInputStream());
    final DataInputStream oProcStdErrStream = new DataInputStream(oProcess.getErrorStream());
    Thread oProcStdOutStreamThread = new Thread()
    public void run()
    try
    String szLine = null;
    while ((szLine = oProcStdOutStream.readLine()) != null)
    System.out.println("[FromProc1] " + szLine);
    catch (Exception ex)
         System.out.println("In oProcStdOutStream");
    ex.printStackTrace();
    oProcStdOutStreamThread.start();
    Thread oProcStdErrStreamThread = new Thread()
    public void run()
    try
    String szLine;
    while ((szLine = oProcStdErrStream.readLine()) != null)
    System.out.println("[FromProc2] " + szLine);
    catch (Exception ex)
    ex.printStackTrace();
    oProcStdErrStreamThread.start();
    // See if the process is still running properly
    int nProcessExitValue = 0;
    try
    nProcessExitValue = oProcess.exitValue();
         // nProcessExitValue = oProcess.waitFor();
         System.out.println("nProcessExitValue : "+nProcessExitValue);
    catch (Exception ex)
    // This means that the process is still running which
    // we'll consider a good sign.
    nProcessExitValue = 0;
    System.out.println("In nProcessExitValue");
    ex.printStackTrace();
    // Check the process exit value
    if (nProcessExitValue != 0)
    throw new Exception("You have insufficient memory to " +
    "launch this program. \nPlease quit some other " +
    "applications and try again.");
    Here is the error :
    starting processs C:\ccc\JRE\bin\javaw.exe com.att.suite.client.SuiteAppManager
    Class loaded...
    Got runtime.....
    nProcessExitValue : 1
    [FromProc2] The java class is not found: com/att/launch/jre/Sample
    java.lang.Exception: You have insufficient memory to launch this program.
    Please quit some other applications and try again.
         at com.att.launch.jre.LaunchApp.spawnProcess(LaunchApp.java:525)
         at com.att.launch.jre.LaunchApp.spawnCJAS(LaunchApp.java:366)
         at com.att.launch.jre.LaunchApp.main(LaunchApp.java:171)
    Please help me, I am struggling with this problem from the long time. Or can any body suggest different way to solve this
    problem instead of downloading the JRE to the client side.
    Bhaskar

  • Compiler says class can't be initialized

    ok, i know abstract classes can't be initialized, but i am extending my base class, but my complier says that "class ClassificationParser can't be initialized" but i am not initializing it. IF anyone can point out a problem, which i just can't see please do. Thank you..
    first is listed the base abstract class, second the extended class
    package cattlemanager.utilities.parsers;
    import java.util.Vector;
    import java.io.File;
    import java.io.IOException;
    * Title:        ClassificationParser
    * Copyright:    Copyright (c) 2001
    * Company:      None
    * @author Harold Smith III
    * @version 1.0
    public abstract class ClassificationParser
       * <p>This method returns the instance of a <code>Classification</code> objects
       * that the implementor can work with and use to there own extent. This allows
       * for the parser to read in all the file data, and insert it into the
       * <code>Classification</code> Objects that he or she wishes the user to
       * modify.</p>
       * <p><strong>Important</strong> - The <code>Vector</code> that is returned will
       *  contain a <code>Vector</code> of <code>Vector</code>'s that the implementor
       *  must work with. The reason for a <code>Vector</code> of <code>Vector</code>'s
       *  is the <code>Classification</code> data may contain several past <code>
       *  Classification</code> records.</p>
       * @return Vector the data vector.
      public Vector getData()
      { return vInternalClassificationDataObject;
       * <code>parse</code> is the default parsing mechanism for the read in data
       * that the user can integrate into there records. Using the <code>parse</code>
       * method, the implemented class will read in the specified <code>File</code>
       * and the <code>Classification</code> Objects will be initialized with tthe
       * read in data.
       * @param File the file to be parsed, should follow the specified format
       *  determined by the appropriate association.
       * @throws WrongFormatException if the file is not formatted to the standards
       *  the association has laid out.
       * @throws IOException if there is a file problem.
      public abstract void parse(File fName) throws WrongFormatException, IOException;
       * The internal <code>Vector</code> of objects that will be laid out as specified
       * in the <code>getData</code> method described within this class.
       * @see #getData
      protected Vector vInternalClassificationDataObject;
    package cattlemanager.utilities.parsers;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.EOFException;
    import java.util.StringTokenizer;
    import java.util.Date;
    import java.util.GregorianCalendar;
    * Title:        HolsteinAssociationClassificationParser
    * Copyright:    Copyright (c) 2001
    * Company:      None
    * @author Harold Smith III
    * @version 1.0
    public class HolsteinAssociationClassificationParser extends ClassificationParser
      private HolsteinAssociationClassificationParser()
      { try
        { parse(new File("demo.ext"));
        catch (Exception e)
       * Doesn't work?!
      public static synchronized ClassificationParser createInstance()
      { return new HolsteinAssociationClassificationParser();
       * <code>parse</code> parses the <a href="www.holstein.com">Holstein
       *  Association</a> classification data as laid out in there <code>File</code>
       *  format. By using this parser, one can read in the records and access the
       *  data that they need.
       * @param File the name of the file to be parsed.
       * @throws WrongFormatException if the file is not properly formated
      private void parse(File fName) throws WrongFormatException, IOException
        try {
          // READ IN FILE
       * Creates an instance of a date for the format specified by the Holstein
       * Association
      private Date createDate(String time)
      { GregorianCalendar c = (GregorianCalendar) GregorianCalendar.getInstance();
        c.set(Integer.parseInt(time.substring(0,4)), Integer.parseInt(time.substring(4,6))-1, Integer.parseInt(time.substring(6,8)));
        return c.getTime();
    }

    ah stupid errors, i figured it out, i accidently created an instance in a class before i decided to change the class to abstract!

  • How to find out class name

    Hi folks,
    Can anybody help me, I got stuck on this problem.
    I need to find out the className of the class, which is specified
    by ordinary filename.
    In other words:
    User gives me filename (something.class) and I need to find out
    classname (I just need to create an instance of this class)
    Thanks a lot.
    sgtPepper

    This will read the class name from a class file.
    * @author Ian Schneider
    public class JavaClassName {
        public static void main(String[] args) throws Exception {
            DataInputStream din = new DataInputStream(new FileInputStream(args[0]));
            int cafebabe = din.readInt();
            if (cafebabe != 0xcafebabe)
                throw new Exception("Not class file");
            din.skip(4);
            int cnt = din.readShort() - 1;
            Object[] info = new Object[cnt];
            for (int i = 0; i < cnt; i++) {
                int b = din.readByte();
                switch (b) {
                    case 1:
                        info[i] = din.readUTF(); break;
                    case 3: case 4: case 9: case 10: case 11: case 12:
                        din.skip(4); break;
                    case 5: case 6:
                        i++;
                        din.skip(8); break;
                    case 7: case 8:
                        info[i] = Short.valueOf(din.readShort()); break;
                    default:
                        assert false;
            din.skip(2);
            int off = din.readShort();
            Number ptr = (Number) info[off - 1];
            System.out.println(info[ptr.intValue() - 1]);
            din.close();
    }

  • Please help with the URL class

    Hello,
    I am trying to write a Java app that will take a url and download it.
    I believe you can do this with the URL class but I don't understand how to. For example, if the http url location points to a picture file, how would I code the app to retrieve this picture and save it to a specified directory?
    Also, is there a way that my java app could open another program, let's say Microsoft Internet Explorer?
    Please be as specific as possible, thanks!

    You'll see below an example to download a file
    private static String copyFile (String url, String nomFichier){
         // construction du fichier de sortie
         File outputFile = new File(repertoire + "\\fichiers\\" + nomFichier);
         // si le fichier existe d�j�, il ne sert � rien de le t�l�charger !
    if (outputFile.exists())
         return "fichiers/" + nomFichier;
              try {     
         HttpURLConnection connect = (HttpURLConnection)new URL(url).openConnection();
    boolean connected = false;
    while (!connected){
    try {
    connect.connect();
    connected = true;
         catch (java.io.IOException e1) { System.out.print("...Tentative de connection"); }     
    DataInputStream reader = new DataInputStream(
    connect.getInputStream());
         FileOutputStream out = new FileOutputStream(outputFile);
         int length = 1024;
         byte[] buf = new byte[length];
         int offset = 0;
         long offsetCourant = 0;
         int nb=0;
         while ((nb=reader.read(buf,offset,length))!= -1) {
              out.write(buf,0,nb);
         out.close();
         catch (java.net.MalformedURLException e) { System.out.println("pb d'url"); }
         catch (java.io.IOException e1) { System.out.println(e1.getMessage()); }
         return "fichiers/" + nomFichier;
    }

  • Caching downloaded classes - again

    I created another thread for this problem, please refer to the original thread "caching downloaded classes".
    Here is the complete code:
    import java.net.*;
    import java.io.*;
    import java.lang.reflect.*;
    class Connect
    public static void main(String...a)
       ClassLoader loader = new NetworkClassLoader();
       try{
           Class<?> c;
           Method m;
           c = loader.loadClass("tryme1");
           m = c.getMethod("p", new Class[]{});
           m.invoke(null,new Object[]{});
          }catch(Throwable t){System.out.println(">>>>>>>> "+t);}
    public static byte[] downloadByteCodesFromURL( DataInputStream in) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        while (true) {
               try {
                    outStream.write(in.readByte());
               catch (IOException e) { 
                      break; 
        return outStream.toByteArray();
    static class NetworkClassLoader extends ClassLoader
    public Class findClass(String name)
    Class c;
    try{
       URL u = new URL("http://localhost:80/"+name+".class");
      InputStream input = u.openStream();
      DataInputStream data = new DataInputStream(input);
      byte classBytes[] = downloadByteCodesFromURL(data);
      c = defineClass(name, classBytes, 0, classBytes.length);
    }catch(Throwable t){System.out.println(t);c = null;}
    return c;
    tryme1.p() calls tryme2.p() which calls tryme3.p(). tryme3.p() just displays a JFrame.
    Sorry, I have a problem with my browser, so I cannot apply code highlighting.
    My question is: will this code cause the JVM to cache the loaded classes?
    Thank you

    Upon your request, I marked this thread as ANSWERED, and I will continue using the original thread.
    But, PLEASE respond because as you can see from the original thread, you didn't answer my question for days, and I had said that I would create a new thread just to award you 10 points for your answer, since I couldn't do that in the original thread because I had already marked it answered for another user.
    I have been on this forum for many years before Oracle acquired Sun. In the old days, I used to get responds form more than one user the same day I post my problem. Now, the volume of posted threads and answers are much less. Are people losing interest in Java or in this forum or something else, I don't know !!!

  • DataInputStream twice on the same InputSrteam

    The code below throws en exception:
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    public class TwiceDataInputStream {
         public static void main(String[] args) throws IOException {
              URL u1 = new URL("http://www.yahoo.com");
              InputStream is1 = u1.openStream();
              DataInputStream dis = new DataInputStream(is1);
              System.out.println(dis.readInt());
              dis.close();
              //NOT AN OPTION!
              //is1 = u1.openStream();
              dis = new DataInputStream(is1);
              //Exception here
              System.out.println(dis.readInt());
              dis.close();
              is1.close();
    }My question is: what should I do to be able to use is1 again?

    However, if you're trying to read from the same stream twice, you can't do it. You could use a PushbackInputStream, I guess, but that would kind of suck. A better approach would be to read once and then provide the bytes to the two different processing entities.

  • Problems implementing abstract classes

    hello.
    this is james mcfadden. I am developing a multiplayer BlackJack card game in Java. the game consists of three programs: BlackJack.java, BlackJackServer.java and BlackJackClient.java (three 3 programs are shown below). i don't know how to implement abstract classes. i am trying to get the BlackJack.java program working with the BlackJackServer.java program. there should be "extends BlackJackServer" somewhere in the BlackJack.java program, but i don't know where.
    import javax.swing.*;
    public class BlackJack extends JPanel{
       public BlackJack(){
          //FlowLayout is default layout manager for a JPanel
          add(new JButton("Hit"));
          add(new JButton("Stay"));
          add(new JButton("New Game"));
       public static void main(String[] args){
          JFrame frame=new JFrame("BlackJack");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(500,500);
          frame.setLocation(200,200);
          BlackJack bj=new BlackJack();
          frame.setContentPane(bj);
          frame.setVisible(true);
    import java.io.*;//Provides for system input and output through data streams, serialization and the file system
    import java.net.*;//Provides the classes for implementing networking applications
    import java.util.*;//Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes
    import java.awt.*;//Contains all of the classes for creating user interfaces and for painting graphics and images
    import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
    public class BlackJackServer extends JFrame{
       private JTextArea jta=new JTextArea();//a text area for displaying text
       public static void main(String[] args){  
              new BlackJackServer();//invokes the constructor BlackJackServer()
       }//end main
       public BlackJackServer(){
          setLayout(new BorderLayout());//places the text area on the frame
          add(new JScrollPane(jta),BorderLayout.CENTER);//lays out a text area, arranging and resizing its components to fit in the centre region;and provides a scrollable view of a lightweight component
          setTitle("BlackJack Server");//Sets the title for this frame to the specified string
          setSize(500,300);//Resizes this component so that it has a width and a height
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Sets the operation that will happen by default when the user closes this frame
          setVisible(true);//shows the frame
          try{
             ServerSocket serverSocket=new ServerSocket(8000);//creates a server socket
             jta.append("Server started at "+new Date()+'\n');//displays the current date in the text area
             Socket socket=serverSocket.accept();//listens for a connection request
             DataInputStream inputFromClient=new DataInputStream(socket.getInputStream());//creates a data input stream
             DataOutputStream outputToClient=new DataOutputStream(socket.getOutputStream());//creates a data output stream
             while(true){
                float bet=inputFromClient.readFloat();//receives bet from the client
                float doublebet=bet+bet;//computes double the bet
                outputToClient.writeFloat(doublebet);//sends double the bet back to the client
                jta.append("Bet received from client: "+bet+'\n');//displays the bet in the text area
                jta.append("Double the bet found: "+doublebet+'\n');//displays double the bet in the text area
             }//end while
          }//end try
          catch(IOException ex){
             System.err.println(ex);//displays an error message
          }//end catch
       }//end constructor
    }//end class BlackJackServer
    import java.io.*;//Provides for system input and output through data streams, serialization and the file system
    import java.net.*;//Provides the classes for implementing networking applications
    import java.awt.*;//Contains all of the classes for creating user interfaces and for painting graphics and images
    import java.awt.event.*;//Provides interfaces and classes for dealing with different types of events fired by AWT components
    import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
    public class BlackJackClient extends JFrame{
       private JTextField jtf=new JTextField();//a text field for receiving text
       private JTextArea jta=new JTextArea();//a text area for displaying text
       private DataOutputStream toServer;//output stream
       private DataInputStream fromServer;//input stream
       public static void main(String[] args){
          new BlackJackClient();//invokes the constructor BlackJackClient()
       public BlackJackClient(){
          JPanel p=new JPanel();//holds the label and text field
          p.setLayout(new BorderLayout());//sets the layout of the content pane of this component by default
          p.add(new JLabel("Enter bet"),BorderLayout.WEST);//displays the bet and lays out a JLabel, arranging and resizing its components to fit in the western region
          p.add(jtf,BorderLayout.CENTER);//lays out the text field, arranging and resizing its components to fit in the centre region
          jtf.setHorizontalAlignment(JTextField.RIGHT);//Sets the horizontal alignment of the text to the right
          setLayout(new BorderLayout());//places the text area on the frame
          add(p,BorderLayout.NORTH);//lays out the text field, arranging and resizing its components to fit in the northern region
          add(new JScrollPane(jta),BorderLayout.CENTER);//lays out a text area, arranging and resizing its components to fit in the centre region;and provides a scrollable view of a lightweight component
          jtf.addActionListener(new ButtonListener());//invokes the ButtonListener class
          setTitle("BlackJack Client");//Sets the title for this frame to the specified string
          setSize(500,300);//Resizes this component so that it has a width and a height
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Sets the operation that will happen by default when the user closes this frame
          setVisible(true);//shows the frame
          try{
             Socket socket=new Socket("localhost",8000);//creates a socket to connect to the server
             fromServer=new DataInputStream(socket.getInputStream());//creates an input stream to receive data from the server
             toServer=new DataOutputStream(socket.getOutputStream());//creates an output stream to send data to the server
          }//end try
          catch(IOException ex){
             jta.append(ex.toString()+'\n');//displays an error message
          }//end catch
       private class ButtonListener implements ActionListener{
          public void actionPerformed(ActionEvent e){
             try{
                float bet=Float.parseFloat(jtf.getText().trim());//gets the bet from the text field
                toServer.writeFloat(bet);//Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream
                toServer.flush();//Flushes this output stream and forces any buffered output bytes to be written out
                float doublebet=fromServer.readFloat();//gets double the bet from the server
                jta.append("Bet is "+bet+"\n");//displays the bet in the text area
                jta.append("Double the bet received from the server is "+doublebet+'\n');//displays double the bet in the text area
             }//end try
             catch(IOException ex){
                System.err.println(ex);//displays an error message
             }//end catch
          }//end method
       }//end class
    }//end class BlackJackClient

    there should be "extends BlackJackServer" somewhere in the BlackJack.java programI very much doubt that.
    It's possible you might need to create a BlackJackServer object or something like that. But I don't see the point in subclassing it.

  • How can I know  the end of DataInputStream when I use readUTF()

    I use the readUTF() method of DataInputStream in client to read String from server
    I use catch EOFExcetpion to let the client know the end of the InputStream(that is when the server close its socket) , however it seems that donen't work
    what can I do ?
    class client
        public void method()
           DataInputStream in=new DataInputStream(socket.getInputStream);
           try{
               try{
                        while(true)
                              String temp= in.readUTF();
                              System.out.println(temp.charAt(.........));
                   }catch( EOFException e){}
               }catch(IOException ioe){}
    }when server closes , it seems that the" System.out.println "sentence keep going
    the above is the simplified version, the original one is too long to put here

    I think the readUTF method will straight away return you the whole content as a string and you don't have to put it in a loop.
    The EOF Exception will be thrown only when the stream reaches the end before reading all the bytes.
    Thanx and Regards,
    Anish K George

  • Java version from class file

    How to decide from class file that which java version (1.3, 1.4 etc) was used to compile it?

    Sorry I made a mistake,
    its minor, major
    Dont we have some utility given by Sun for this?
    javap -verbose <classname>will print out versions plus more...
    Do I need to use InputStream for reading class file then see the version?
    DataInputStream din = new DataInputStream(new FileInputStream(classFile));
    din.readInt();
    short minor = din.readShort();
    short major = din.readShort();Why do you need to do this?

Maybe you are looking for

  • Windows Server 2008 R2 - You might not have permission to use this network resource. The request is not supported.

    Hello ! I have a server with Windows Server 2008 R2 (AD, File Server, DNS Server and DHCP Server) that not access network share other Domain Controller. Well, is very crazy. I view network shares by network computers and devices, but not \\domain_con

  • Can't create rescue disk nor boot from installation disk

    I can't make a rescue disk.  Get an error message.  As instructed I booted from the Windows 7 install disc and it comes up with no mouse or keyboard support.  What is displayed is the choice of languages. Can't get a command prompt. Am I missing some

  • Logical Agregated Column with formula

    Hi all, I need to create an agregated column of a field that have a formula. I know you haven't understood anything so here is an example :) Source Table: A B C 001 'ZZ' 'ZZ' 001 'ZZ' 'ZZ' 001 'ZZ' 'YY' 002 'XX' 'TT' 003 'JJ' 'JJ' Desired Result: (E

  • Dreamweaver8, MySQL....

    Hey guys i need your help please, i'm in a bit of confused. I'm building a vehicle rental system and I have created a database using MySQL that i'm successfully connecting to through dreamweaver 8 I have the following at the moment : select Location

  • [svn:fx-trunk] 15314: Merging revision 15312 from 4.x to trunk

    Revision: 15314 Revision: 15314 Author:   [email protected] Date:     2010-04-09 14:02:53 -0700 (Fri, 09 Apr 2010) Log Message: Merging revision 15312 from 4.x to trunk ComboBox bug fix http://bugs.adobe.com/jira/browse/SDK-26089 - s:ComboBox is not