Reflection - reading a .class file

I want to read in a .class file, and be able to use reflection to get a list of that class's methods. I'm using a JFileChooser to find the file, I just need to know how to use the output from the JFileChooser (a path to the file) to load the file into the program, and use reflection methods to create an appropriate Class object.

kajbj wrote:
fredley_m wrote:
kajbj wrote:
fredley_m wrote:
I don't think I'm making myself clear. I can read in a file, I don't know how to use reflection on a .class file. I need to know how to complete the following line of code:
Class reflectedClass =reflectedClass should then contain a copy of the class from the .class file.You load a class using Class.forName(..)This does not work.
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(main_panel);
     if(returnVal == 0)
          String fileName = fc.getSelectedFile().getName();
          fileName = fileName.substring(0,fileName.lastIndexOf('.')); //also doesn't work without this line
          Class c = Class.forName(fileName);
...I get a ClassNotFoundException when I try to open MyClass.classYou need to know about how class loaders work, and use one. Read the javadoc:
[http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html]
The NetworkClassLoader sample is pretty close to what you want.Thanks, the URLClassLoader is perfect, however my code:
String fileName = fc.getSelectedFile().getName();
fileName = fileName.substring(0,fileName.lastIndexOf('.'));
URL[] urls = {new URL(filePath)};
URLClassLoader cl = new URLClassLoader(urls);
Class c = cl.findClass(fileName);does not compile: "findClass has protected access"

Similar Messages

  • Can Java reflect not only .Class file

    Hi' i'm newbie in this topic, i'm really appreciate if somebody can help me..cos i'm really stuck in here...
    My Problems are :
    1. i want to ask about this, can Java reflect from .java file?
    2. i'm using Eclipse IDE, i'm really interesting about how JTree or Package Explorer in Eclipse can always displaying update information about class structure? but .java files not compiled, how can? if Eclipse using reflection, .java files must be compiled first, correct me if i'm wrong?
    The fact is Eclipse don't have to compiled .java files to get the update information about class structure and displaying in JTree or package Explorer...how implement like this?
    what i mean like this :
    ex : if i type int x = 100; (not only int, it could be anything else..) at the working files, JTree or Package Explorer in Eclipse can always update the informasion about class structure, but .java files not compiled..
    i hope my question are easy to understand, i really need some help..
    Thanks a lot..

    hey, thanks for the answers, but i would like to ask :
    1) Eclipse performs background compilation of the Java sources, then performs reflection on those temporary classes++ if i'm using this way, how about the performance? seems that it will be compiled all the time right?
    2) Eclipse has access to the results of the Java source code parser, and can extract the information from the java syntax parser, before it gets to the compilation stage.++ how to implement this? what do you mean about java syntax parser?
    do you know where i can find any article about this?
    thanks a lot again...

  • �How do i do reflection on a *.class file or a *.java?

    i have been readin the tutorial on how to do reflection but at the begining they say i need the classname. i don't have the classname, i just have the complete path to the file plus the filename.
    Class c = Class.forName(className);
    Object o = c.newInstance();Edited by: Tequila_Burp on Jun 16, 2008 9:21 PM

    What am trying to do is to extract all the methods information from a web service by knowing the URL and if necessary the namespace and servicename (until now it has been necessary). I had been forced to use Java Source Reflection from jaxme =/
    This code does the job but am unsure if there is an easier and effective method.
    The problem here is generarClases. When I take out the commentary it does its job but just when it finish generating the *.java files the application suddently shutdown. wsimport is shutting down all the application.
    This code is still incomplete
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package com.monitor;
    import com.beans.MethodBean;
    import com.beans.ParameterBean;
    import com.beans.WebServiceInfoBean;
    import com.sun.tools.ws.WsImport;
    import java.io.File;
    import java.net.URL;
    import java.util.Iterator;
    import javax.xml.namespace.QName;
    import javax.xml.rpc.Call;
    import javax.xml.rpc.Service;
    import javax.xml.rpc.ServiceFactory;
    import org.apache.ws.jaxme.js.JavaMethod;
    import org.apache.ws.jaxme.js.JavaSource;
    import org.apache.ws.jaxme.js.JavaSourceFactory;
    import org.apache.ws.jaxme.js.util.JavaParser;
    * @author Tequila_Burp
    public class webservicemonitor {
        public webservicemonitor() {
        public WebServiceInfoBean getWebServiceInfo(WebServiceInfoBean WebServiceInfo) {
            String wsdlURL = WebServiceInfo.getwsdlURL();
            String namespace = WebServiceInfo.getnamespace();
            String serviceName = WebServiceInfo.getserviceName();
            //generarClases(wsdlURL);
            QName serviceQN = new QName(namespace, serviceName);
            try {
                ServiceFactory serviceFactory = ServiceFactory.newInstance();
                Service service = serviceFactory.createService(new URL(wsdlURL), serviceQN);
                Iterator i = service.getPorts();
                while (i.hasNext()) {
                    QName sQN = (QName) i.next();
                    Call[] calls = service.getCalls(sQN);
                    for (int j = 0; j < calls.length; j++) {
                        String name = calls[j].getOperationName().getLocalPart();
                        MethodBean method = new MethodBean();
                        File newFile1 = new File("C:/Documents and Settings/Tequila_Burp/Escritorio/WebServiceMonitor/wsdl/" + namespace + "/" + name + ".java");
                        method = FillParameters(newFile1, method);
                        WebServiceInfo.getmethods().add(method);
                    File newFile2 = new File("C:/Documents and Settings/Tequila_Burp/Escritorio/WebServiceMonitor/wsdl/" + namespace + "/" + serviceName + "SOAP.java");
                    WebServiceInfo = FillMethodsReturnType(newFile2,WebServiceInfo);
                WebServiceInfo = ArmarFirma(WebServiceInfo);
            } catch (Exception e) {
                System.out.println("Error: " + e.getMessage());
            return WebServiceInfo;
        private void generarClases(String URL) {
            WsImport ws = new WsImport();
            String[] s = new String[5];
            s[0] = "-d";
            s[1] = "wsdl";
            s[2] = "-s";
            s[3] = "wsdl";
            s[4] = URL;
            try {
                ws.main(s);
            } catch (java.lang.Throwable e) {
        private MethodBean FillParameters(File pFile, MethodBean method) {
            try {
                JavaSourceFactory jsf = new JavaSourceFactory();
                JavaParser jp = new JavaParser(jsf);
                jp.parse(pFile);
                for (Iterator iter = jsf.getJavaSources(); iter.hasNext();) {
                    JavaSource js = (JavaSource) iter.next();
                    method.setname(js.getClassName());
                    JavaMethod[] methods = js.getMethods();
                    boolean bool = true;
                    for (int i = 0; i < methods.length; i++) {
                        if (methods.getProtection().equals(JavaSource.PUBLIC) && bool) {
    ParameterBean par = new ParameterBean();
    par.setname(methods[i].getName());
    par.settype(methods[i].getType().getClassName());
    method.getparameters().add(par);
    if (bool) { bool = false; } else { bool = true; }
    } catch (Exception e) {
    e.printStackTrace();
    return method;
    private WebServiceInfoBean FillMethodsReturnType(File pFile, WebServiceInfoBean WebServiceInfo) {
    try {
    JavaSourceFactory jsf = new JavaSourceFactory();
    JavaParser jp = new JavaParser(jsf);
    jp.parse(pFile);
    for (Iterator iter = jsf.getJavaSources(); iter.hasNext();) {
    JavaSource js = (JavaSource) iter.next();
    JavaMethod[] methods = js.getMethods();
    for (int i = 0; i < methods.length; i++) {
    if (methods[i].getProtection().equals(JavaSource.PUBLIC)) {
    WebServiceInfo.getMethod(i).setreturnType(methods[i].getType().getClassName());
    } catch (Exception e) {
    e.printStackTrace();
    return WebServiceInfo;
    private WebServiceInfoBean ArmarFirma(WebServiceInfoBean WebServiceInfo)
    for (int i = 0; i < WebServiceInfo.getmethods().size(); i++)
    StringBuilder sb = new StringBuilder();
    MethodBean method = WebServiceInfo.getMethod(i);
    sb.append("public " + method.getreturnType() + " " + method.getname() + "(");
    for (int j = 0; j < method.getparameters().size(); j++)
    ParameterBean parameter = method.getParameter(j);
    sb.append(parameter.gettype() + " ");
    sb.append(parameter.getname());
    if (j + 1 != method.getparameters().size())
    sb.append(", ");
    sb.append(")");
    method.setfirma(sb.toString());
    return WebServiceInfo;

  • How to read the java class file to convert it in java.

    hello all,
    i m developing the java application which generated the java code from the java 'class file' .
    Can anybody please help me, Is any java support for reading the class file? or how to know the class file format?
    I know the application javad, jad, javap which is doing the same thing.
    thanks for reply,
    - Jayd

    do you mean decompiling? there are tons of java decompilers available out there, what exactly are you trying to do here?

  • Getting the class name from within the compiled class file

    hey!
    I was wondering (i know its possible) how to read a .class and get the name of the class. ok that made not much sense^^ so, You have a file: c:\f.class but it wont run because the file name has to be the same as the classes name, right? so how can you read the class file i guess in binary mode to receive the correct class name.
    I saw inside my f.class i have "realname.java" so i know now that the name of the class file should be realname.class, i tried ways to extract it from the class file but never had any success.
    i think i need to study english^^
    ps: i need this because i have some class files sent to me and the file names have been changed so they wont work, they only work when i open the class file in notepad and find out what its real name should be and then rename the file.
    Edited by: forgotmydamnpass on May 7, 2009 11:23 AM

    ah looks interesting, problem is i cant use it.. im prone to errors!
    import java.net.URLClassLoader;
    public class NewMain {
         * @param args the command line arguments
        public static void main(String[] args) {
            FileClassLoader loader = new FileClassLoader();
            Class clazz = loader.createclass("c:\\f.class");
            Method method = clazz.getName();
    }apparently "createclass" doesnt exist :/
    FileClassLoader = cannot find symbol
    Method = cannot find symbol

  • How do I alter the bytes of a Class file to add calls to the methods?

    If i had the bytes of a class file, and I wanted to alter the bytes that constitute each method for the class so that it included a call to the security manager, how would i do it?
    1. How would I know which bytes were the opening of a method?
    2. how would I know what the name of the method is?
    3. How would I create bytes for something like:
       SecurityManager sm = System.getSecurityManager().checkPermission(thismeth, subject);
    4. I assume that if by some miracle I can do the above, then all I have to do is call defineClass(...) in ClassLoader and send it the new bytes, right?
    Thanks to all!

    OK, if it will help anyone get me the answers here, I found a class on the internet that can read a class file and tell you where in the bytes a method occurs and what its name is, and how long it is. What I need now is how to convert a call into the correct manner of bytes.
    For example, so I could add the bytes that would do:
       System.out.println("Added!");
    The class that reads a class file:
    /* Inspector.java by Mark D. LaDue */
    /* June 24, 1997 */
    /* Copyright (c) 1997 Mark D. LaDue
       You may study, use, modify, and distribute this example for any purpose.
       This example is provided WITHOUT WARRANTY either expressed or implied.  */
    /* This Java application analyzes the entries in the constant pool and locates
       the code arrays in a Java class file. Each entry in the constant pool
       yields the following information:
       Index     Tag     Reference(s)/Value(s)
       where "Index" is its position within the class file's constant pool,
       "Tag" is the official tag number for that type of entry, and
       "Reference(s)/Value(s)" contains the constant pool information
       according to the entry's type.  (See Lindholm and Yellin's "The Java
       Virtual Machine Specification" for details.)  For each code array in
       the class file, its starting byte, its total length, and the name of
       the method in which it occurs are given.  Combining this information
       with the information yielded by the humble "javap" utility gives one
       sufficient information to hack the code arrays in Java class files. */
    import java.io.*;
    class Inspector {
        public static void main(String[] argv) {
            int fpointer = 8; // Where are we in the class file?
            int cp_entries = 1; // How big is the constant pool?
            int Code_entry = 1; // Where is the entry that denotes "Code"?
            int num_interfaces = 0; // How many interfaces does it use?
            int num_fields = 0; // How many fields are there?
            int num_f_attributes = 0; // How many attributes does a field have?
            int num_methods = 0; // How many methods are there?
            int num_m_attributes = 0; // How many attributes does a method have?
            int[] tags; // Tags for the constant pool entries
            int[] read_ints1; // References for some constant pool entries
            int[] read_ints2; // References for some constant pool entries
            long[] read_longs; // Values for some constant pool entries
            float[] read_floats; // Values for some constant pool entries
            double[] read_doubles; // Values for some constant pool entries
            StringBuffer[] read_strings; // Strings in some constant pool entries
            int[] method_index;
            long[] code_start;
            long[] code_length;
    // How on earth do I use this thing?
            if (argv.length != 1) {
                System.out.println("Try \"java Inspector class_file.class\"");
                System.exit(1);
    // Start by opening the file for reading
            try {
                RandomAccessFile victim = new RandomAccessFile(argv[0], "r");
    // Skip the magic number and versions and start looking at the class file
                victim.seek(fpointer);
    // Determine how many entries there are in the constant pool
                cp_entries = victim.readUnsignedShort();
                fpointer += 2;
    // Set up the arrays of useful information about the constant pool entries
                tags = new int[cp_entries];
                read_ints1 = new int[cp_entries];
                read_ints2 = new int[cp_entries];
                read_longs = new long[cp_entries];
                read_floats = new float[cp_entries];
                read_doubles = new double[cp_entries];
                read_strings = new StringBuffer[cp_entries];
    //Initialize these arrays
                for (int cnt = 0; cnt < cp_entries; cnt++) {
                    tags[cnt] = -1;
                    read_ints1[cnt] = -1;
                    read_ints2[cnt] = -1;
                    read_longs[cnt] = -1;
                    read_floats[cnt] = -1;
                    read_doubles[cnt] = -1;
                    read_strings[cnt] = new StringBuffer();
    // Look at each entry in the constant pool and save the information in it
                for (int i = 1; i < cp_entries; i++) {
                    tags[i] = victim.readUnsignedByte();
                    fpointer++;
                    int skipper = 0;
                    int start = 0;
                    int test_int = 0;
                    switch (tags) {
    case 3: read_ints1[i] = victim.readInt();
    fpointer += 4;
    break;
    case 4: read_floats[i] = victim.readFloat();
    fpointer += 4;
    break;
    case 5: read_longs[i] = victim.readLong();
    fpointer += 8;
    i++;
    break;
    case 6: read_doubles[i] = victim.readDouble();
    fpointer += 8;
    i++;
    break;
    case 7:
    case 8: read_ints1[i] = victim.readUnsignedShort();
    fpointer += 2;
    break;
    case 9:
    case 10:
    case 11:
    case 12: read_ints1[i] = victim.readUnsignedShort();
    fpointer += 2;
    victim.seek(fpointer);
    read_ints2[i] = victim.readUnsignedShort();
    fpointer += 2;
    break;
    // This is the critical case - determine an entry in the constant pool where
    // the string "Code" is found so we can later identify the code attributes
    // for the class's methods
    case 1: skipper = victim.readUnsignedShort();
    start = fpointer;
    fpointer += 2;
    victim.seek(fpointer);
    for (int cnt = 0; cnt < skipper; cnt++) {
    int next = victim.readUnsignedByte();
    switch (next) {
    case 9: read_strings[i].append("\\" + "t");
    break;
    case 10: read_strings[i].append("\\" + "n");
    break;
    case 11: read_strings[i].append("\\" + "v");
    break;
    case 13: read_strings[i].append("\\" + "r");
    break;
    default: read_strings[i].append((char)next);
    break;
    victim.seek(++fpointer);
    victim.seek(start);
    if (skipper == 4) {
    fpointer = start + 2;
    victim.seek(fpointer);
    test_int = victim.readInt();
    if (test_int == 1131373669) {Code_entry = i;}
    fpointer = fpointer + skipper;
    else {fpointer = start + skipper + 2;}
    break;
    victim.seek(fpointer);
    // Skip ahead and see how many interfaces the class implements
    fpointer += 6;
    victim.seek(fpointer);
    num_interfaces = victim.readUnsignedShort();
    // Bypass the interface information
    fpointer = fpointer + 2*(num_interfaces) + 2;
    victim.seek(fpointer);
    // Determine the number of fields
    num_fields = victim.readUnsignedShort();
    // Bypass the field information
    fpointer += 2;
    victim.seek(fpointer);
    for (int j=0; j<num_fields; j++) {
    fpointer += 6;
    victim.seek(fpointer);
    num_f_attributes = victim.readUnsignedShort();
    fpointer = fpointer + 8*(num_f_attributes) + 2;
    victim.seek(fpointer);
    // Determine the number of methods
    num_methods = victim.readUnsignedShort();
    fpointer += 2;
    // Set up the arrays of information about the class's methods
    method_index = new int[num_methods];
    code_start = new long[num_methods];
    code_length = new long[num_methods];
    //Initialize these arrays
    for (int cnt = 0; cnt < num_methods; cnt++) {
    method_index[cnt] = -1;
    code_start[cnt] = -1;
    code_length[cnt] = -1;
    // For each method determine the index of its name and locate its code array
    for (int k=0; k<num_methods; k++) {
    fpointer += 2;
    victim.seek(fpointer);
    method_index[k] = victim.readUnsignedShort();
    fpointer += 4;
    victim.seek(fpointer);
    // Determine the number of attributes for the method
    num_m_attributes = victim.readUnsignedShort();
    fpointer += 2;
    // Test each attribute to see if it's code
    for (int m=0; m<num_m_attributes; m++) {
    int Code_test = victim.readUnsignedShort();
    fpointer += 2;
    // If it is, record the location and length of the code array
    if (Code_test == Code_entry){
    int att_length = victim.readInt();
    int next_method = fpointer + att_length + 4;
    fpointer += 8;
    victim.seek(fpointer);
    code_length[k] = victim.readInt();
    code_start[k] = fpointer + 5;
    fpointer = next_method;
    victim.seek(fpointer);
    // Otherwise just skip it and go on to the next method
    else {
    fpointer = fpointer + victim.readInt() + 4;
    victim.seek(fpointer);
    // Print the information about the Constant Pool
    System.out.println("There are " + (cp_entries - 1) + " + 1 entries in the Constant Pool:\n");
    System.out.println("Index\t" + "Tag\t" + "Reference(s)/Value(s)\t");
    System.out.println("-----\t" + "---\t" + "---------------------\t");
    for (int i = 0; i < cp_entries; i++) {
    switch (tags[i]) {
    case 1: System.out.println(i + "\t" + tags[i] + "\t" + read_strings[i].toString());
    break;
    case 3: System.out.println(i + "\t" + tags[i] + "\t" + read_ints1[i]);
    break;
    case 4: System.out.println(i + "\t" + tags[i] + "\t" + read_floats[i]);
    break;
    case 5: System.out.println(i + "\t" + tags[i] + "\t" + read_longs[i]);
    break;
    case 6: System.out.println(i + "\t" + tags[i] + "\t" + read_doubles[i]);
    break;
    case 7:
    case 8: System.out.println(i + "\t" + tags[i] + "\t" + read_ints1[i]);
    break;
    case 9:
    case 10:
    case 11:
    case 12: System.out.println(i + "\t" + tags[i] + "\t" + read_ints1[i] + " " + read_ints2[i]);
    break;
    System.out.println();
    // Print the information about the methods
    System.out.println("There are " + num_methods + " methods:\n");
    for (int j = 0; j < num_methods; j++) {
    System.out.println("Code array in method " + read_strings[method_index[j]].toString() + " of length " + code_length[j] + " starting at byte " + code_start[j] + ".");
    System.out.println();
    // All the changes are made, so close the file and move along
    victim.close();
    } catch (IOException ioe) {}

  • Problems on zipping and unzipping class files

    I am trying to add a class file to a new jar file using FileInputStream and JarOutputStream.
    I am getting a very unique problems.
    when I read a class file using FileInputStream from my local hard disk I am getting 30 bytes less than then actual file size (the difference in bytes is exactly 30 bytes for any file, either class or xml or java, I dont understand this concept). after reading the contents I am writing the bytes read to a jar file using JarOutputStream. This all gets done fine. But when I extract the class file written into the jar file and try to run the class it is giving me the exception as follows:
    java.lang.ClassNotFoundException: com.wipro.flowbrix.plugins.factory.NewClass
    Exception in thread "main" java.lang.ClassFormatError: com/wipro/flowbrix/plugins/factory/NewClass (Bad magic number)
    at java.lang.ClassLoader.defineClass0(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    The classpath to the folder from where I am running the file is set. I have double checked the classpath.
    any information or solutions regarding this would be of great help.

    A "magic number" is a short sequence of data at the beginning of a file used to identify the file. ".class" files, for instance, always start with OxCA, 0xFE, 0xBA and 0xBE.
    If the 30 bytes missing are at the beginning of your file, there's nothing suprising in getting a "ClassFormatError" exception.
    I think we should concentrate on your first problem. Can you post the code used to add the class file, please?
    /Stephane

  • Class file are readable?

    Hi...wise guys!
    Can we open / read a class file like *.class?
    I am using JCreator to open, read, create and compile a java files...but class file won't.
    thanks in advance.

    @Op. Why would you like to look at the class file?
    KajInquisitive to see what it contains. Even i was when
    i was learning java initially because of the habit of
    reading too much intel machine code(That was when i
    was designing assembler for a 8086).Yup...i want to see it contains, and what happen after compiling the java files.
    Any decompiler can do this for me?

  • Loading .class files for reflection

    I'm trying to write a program that lets the user select thier .class files to gather
    information about those classes with reflection.
    I can't figure out how to get ClassLoader to load .class files outside the program
    directory.

    I've tried both these options, and spent some time on it too,
    but failed. If can't find a class that can load clases form a URL
    how can I write my own ClassLoader that does it.
    The ClassLoaders all seem to assume that they already know where
    to look for the class files. Perhaps if I could tell them where to look,
    but I don't see how.

  • Reading & writing binaries(.class files)

    folks,
    how does one go about reading and writing .class files in java. I am able to write 'em only in ASCII format which is not what i want.
    Thanks!

    Did anybody say anything about disassembling?He wants to read and write class files, it's the title of the post.
    I don't appreciate you dismissing my suggestions like that.
    There's plenty of gotchas in reading and writing class files, such as Longs & Doubles taking up 2 positions in the constant pool.
    Hence the reason why I suggested using an open source library like BCEL or ASM. These are still valid as class readers, even if you don't touch the byte code. ( disassembly )
    But what would I know Ejp....sure I only wrote my own Java 1.5 class reader / disassembler.

  • CX Archive class file signature change is not reflected in event binding

    I have a CX archive file (.jar). I added a method to one of the class files in it and reuploaded to the archive. But, when I create a CX rule and specify event binding, this new method is not visible in the available list. What could be the cause of this issue and what is the resolution. Thanks.

    Its the way configurator works.
    First it checks in the middeltier java classpath if the class exists and if not, then look into archive to find the class.
    Archive has advantage like if you change the jar, you dont need to bounce the instance (need bounce for changing file on MT).
    Many developer will not have access to put the file on middle-tier, they can easily upload on archive.
    Archive will get moved automatically to target when you publish the model (MT file migration has to be done manually to publication target)

  • Error in reading .class files

    What kind of program opens .class files?
    i'm new to java technology and am very confused with all these.
    Can someone please help?
    .class files ...
    i think its got something to do with JVM
    please send me instructions on how to run .class files
    thanks

    You need java.exe from the JRE or J2SDK. You can find the download links on the front page of http://java.sun.com. At its simplest, if your class file is called MyProgram.class, you would run it with the command "java MyProgram".

  • Where to place an xml file that is read by  java class file  dir structure

    Hello all,
    I have an xml file that I am using in lieu of a database to track conference rooms . This is a small file. I need to read this file from my java class file which is used by a jsp. Currently I have an absolute path C://logger/conference.xml. All works fine but I need to deploy to a different machine soon and so I need to place this file somewhere in the project directory structure (created by netbeans) so that it will be included in the war file and can be read by the java class file.
    Also what would be the relative path to this suggested directory.
    TIA!!!

    public class DOMconference {
        /** Creates a new instance of DOMconference */
        public DOMconference() { }
        //private final static String XML_FILE_NAME = "/opt/conference.xml";//set the output file and location
        public String XML_FILE_NAME = "";
        private final static String FIRST_CONF_ID = "8200";//set the initial conference number
        static Document document;
        public void getFilePath(String path)
            XML_FILE_NAME = path.replaceAll("\\\\","/");
            System.out.println("XML==============="+XML_FILE_NAME);
        File file = new File(XML_FILE_NAME);
        *generic method that returns a Document object
       public Document getDocument() throws SAXException, ParserConfigurationException,
               IOException
           DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
           factory.setIgnoringComments(true);
           factory.setCoalescing(true);
           factory.setNamespaceAware(false);
           factory.setValidating(false);
           DocumentBuilder builder = factory.newDocumentBuilder();
           document = builder.parse(file);   //HERE IS WHERE THE ERROR POINT S TO
           return document;
       }Here is the complete error:
    INFO: Server startup in 1282 ms
    XML===============C:/Documents and Settings/gforte/agi/build/web/WEB-INF/conference.xml
    [Fatal Error] bin:1:1: Content is not allowed in prolog.
    org.xml.sax.SAXParseException: Content is not allowed in prolog.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:264)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:292)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:172)
    at agi.DOMconference.getDocument(DOMconference.java:91)
    at agi.DOMconference.getLdapConferences(DOMconference.java:466)
    at agi.Ldap.getConferences(Ldap.java:243)
    at org.apache.jsp.test_jsp._jspService(test_jsp.java:111)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:362)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
    at java.lang.Thread.run(Thread.java:595)
    [Fatal Error] bin:1:1: Content is not allowed in prolog.
    NotifyUtil::java.net.SocketException: Software caused connection abort: recv failed
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:129)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
    at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:313)
    at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:606)
    at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:554)
    at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:571)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:936)
    at org.netbeans.modules.web.monitor.server.NotifyUtil$RecordSender.run(NotifyUtil.java:248)
    So if I change my code to this (note that all I change is how the constant XML_FILE_NAME is set and I copy and paste the path that is derived from getFilePath after the String.replaceAll call.):
    public class DOMconference {
        /** Creates a new instance of DOMconference */
        public DOMconference() { }
        private final static String XML_FILE_NAME = "C:/Documents and Settings/gforte/agi/build/web/WEB-INF/conference.xml";//set the output file and location
        //public String XML_FILE_NAME = "";
        private final static String FIRST_CONF_ID = "8200";//set the initial conference number
        static Document document;
        public void getFilePath(String path)
            //XML_FILE_NAME = path;//.replaceAll("\\\\","/");
            System.out.println("XML==============="+XML_FILE_NAME);
        File file = new File(XML_FILE_NAME);
        *generic method that returns a Document object
       public Document getDocument() throws SAXException, ParserConfigurationException,
               IOException
           DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
           factory.setIgnoringComments(true);
           factory.setCoalescing(true);
           factory.setNamespaceAware(false);
           factory.setValidating(false);
           DocumentBuilder builder = factory.newDocumentBuilder();
           document = builder.parse(file);
           return document;
       }All is fine..
    Just in case, here is my xml file contents copy and paste from notepad.
    <?xml version="1.0"?><conf_rooms><conf_room><conf_id>8200</conf_id><conf_name>Conference room 1</conf_name></conf_room><conf_room><conf_id>8201</conf_id><conf_name>Conference Room 2</conf_name></conf_room><conf_room><conf_id>8202</conf_id><conf_name>dufus</conf_name></conf_room></conf_rooms>Thanks for hanging in there with me on this.
    Graham

  • Interface Designer: "Reading Class File" fails

    I'm just trying the Apple Cocoa Tutorial (ConcurrencyConverter). I have a problem at the point where you shall load the class file "ConverterController.h" into the Interface Designer. It always fails with the error "Parsed 1 source file, but no buttons were found...".
    Even when I copy and paste the header file from the tutorial it doesn't work. It looks like this:
    #import <Cocoa/Cocoa.h>
    @interface ConverterController : NSObject {
    IBOutlet NSTextField *amountField;
    IBOutlet NSTextField *dollarField;
    IBOutlet NSTextField *rateField;
    - (IBAction)convert:(id)sender;
    @end
    I have no idea what to do now, can you help me?

    digitalformula wrote:
    Your note about the outlets etc actually being there but needing to look harder made me stare at the screen for a few minutes ... I can't see them though.
    Maybe they just don't show up in Xcode 3.2.1???
    Hi DF -
    I don't know how to guide you further since I don't have 3.2.1. Did you see Ruud's most recent post?
    Ruud Wijnands wrote:
    ... if you click on the connections tab they are shown there in in unconnected state.
    Assuming this much hasn't changed since 3.1.4, besides the Class Outlets table in the Identity Inspector, there are two places to look for Outlet and Action connections:
    1) When you ctrl-click on an object (e.g. the icon for a controller), a black, floating panel should come up listing all connections from and to that object. Be sure to select the object in the xib (icon) window with the View Mode switch in the Center position. With that View Mode setting, the xib window should display a two column table with a tree of small icons to the left. By expanding the nodes in that tree you should be able to find every object in the xib;
    2) When you select an object (in the xib window as above), the Connections Inspector (cmd-5) should display all possible connections from and to the object. I assume this is the view Ruud referred to as "the connections tab".
    I don't recall seeing a case where the black panel list differed from the list shown in the Connections Inspector, but it wouldn't hurt to look at both. If neither of the above finds the connections when _you've seen your custom class in the Identity list, and set the object in question to that class_, I might suggest closing the xib and restarting IB. You could also try modifying and resaving your custom object's @interface file just to stir things up a bit (e.g., remove all the IBOutlet declarations, save, then add them and resave).
    It might also help to start a new project and do nothing else but add one custom class to see if you have better luck getting IB to import the correct connections in the new context. E.g., add a NSObject subclass named Foo with one ivar such as IBOutlet NSWindow *Bar; then see if you can add a blue cube to MainMenu.xib, set its identity to Foo class and see the Bar outlet.
    For more details on connecting custom objects, see "Setting the Class of an Object" and "Injecting Class Information into a Nib File" under Xcode Integration in the +Interface Builder User Guide+.
    Of course it's possible we're dealing with a bug that's unique to 64-bit 3.2.1. I've searched the web, the 3.2.1 Release Notes and the Xcode Mailing List for reports that might confirm this, but haven't found anything interesting yet. So I think we should continue to assume that Xcode 3.2.1 is capable of obtaining custom class info, and we're just dealing with some misunderstanding. Hopefully, one of our forum experts who has 3.2.1 will join the thread to shed some more light on the topic.
    \- Ray

  • Importing my class files from another folder

    hello everybody ,im creating a software package for a new company and want to organise my class files into different folders so that it would be easier for someone to navigate through them and update if necessary ,how do i import an instance of a class in a file that is in a subfolder of the folder that contains the class that is calling it.(sorry for being a bit long winded) iv tried diff things and they didn't work.
    At the moment i have all the files in the one folder,but as i said above want to put them into appropriate folders.
    I would be very gratefull if someone could give me some examples and if not some appropriate links,thanks iv tried looking for this on the net but could not find anything.

    What you should probably do is to organise your classes into a heirarchy of packages not merely folders. Java expects the package structure to be reflected in the directory structure holding both the source and class files. If it's looking for a class called, say, com.mycompany.widgets.MainWidget it expects to find it in a directory com//mycompany/widgets relative the the directory on the class path.
    Use the package directive in each source file to indicate the package path.

Maybe you are looking for

  • URGENT HELP-Connecting 2 Switches

    Hi All, I need to connect 2 switches (2960 & 2960S) with only one single link in our LAN network. This is to get extra number of ports. Requesting your help with the followings: Please confirm if straight throug cable will work to connect between the

  • Multiple Result Set Using Nested Table

    Package declaration------------ CREATE or REPLACE PACKAGE dummy AS TYPE CResValues IS TABLE OF VARCHAR2(2000); FUNCTION GetValue(p_user IN VARCHAR2, p_owner IN VARCHAR2, p_resource IN VARCHAR2, ResValues OUT CResValues) RETURN INTEGER; END dummy; Pac

  • MacBook Air stolen recently. Can I re-install my purchased standalone LR5 onto a new laptop?

    I purchased a standalone version of LR5 in February of this year.My  MacBook Air was stolen a few days ago (so sad), and I want to know - can re-install LR5 onto a new laptop (I have the serial number and my previous laptop was the first installation

  • Hiii select option validation on screen

    Hi please advise how do i do check on selection screen Suppose i have a internal table ITAB which has value as below ITAB--> BUKRS----CODE AA-------01 AA-------08 AA-------07 BB-------03 BB-------04 i have on selection screen as below: Paremeters: P_

  • Close current tab through a button

    All, I have a weird behavior in my ADF page. I have a method to close the current tab. When i set this method as Action Listener for a commandMenuItem , its working fine. But when i set this method as Action listener for a button , its throwing nullP