Extend java.io.File

Is it possible to expend File with this constructor?
     public MP3File( File f ) {
//blah blah...
Guess not, it gives me an error....any suggestion?

What was the error message you received. Also show the complete class structure, in that to say, just mention the class definition and the method signatures you have used. Also java.io.File is not a final class which means you can extend File. You cant similarly extend java.lang.String because its a final class.

Similar Messages

  • How to extend java.io.File class?

    Hi,
    I have written the following code.
    import java.io.*;
    public class MyFile extends java.io.File {
    MyFile()
    } // end myFile class
    I am getting the following errors while compiling. Could any one throw some light on this and tell me what could be the wrong in this?
    C:\>javac MyFile.java
    MyFile.java:5: cannot resolve symbol
    symbol : constructor File ()
    location: class java.io.File
    ^
    1 error
    Appreciate your help in this regard. Please email me if you find the answer for this.
    Thanks & Regards,
    Murthy
    Email: [email protected]

    there's no default File() constructor , so u should write like this:
    import java.io.*;
    public class MyFile extends File {
         MyFile(String name) {
              super(name);
    } // end myFile class
    ------------------------

  • Java.io.File

    Hello i created a class that extends java.io.File
    public Class MyClass extends File
    After i created instances of MyClass to populate a tree, i want to put a label ans icons for it and i proceed this way:
    public String getText(Object element) {
              if(element instanceof MyClass) {
                   return ((MyClass)element).getName();
              } else {
                   System.out.println("element is not an instance of MyClass");
                   return ((File)element).getName();
         }Someone can tell why it is not an instance of my class?

    So is there somebody to help me please....
    I got the root of my tree like this Session.getRoot()
    Here is the code for Session
    public class Session {
         private static MyClass logesco;
         public static final String PATH = System.getProperty("user.home") + File.separator;
         public Session() {
              super();
              logesco = new MyClass(PATH, "logesco");
              if(!logesco.exists() && !logesco.isDirectory()) {
                   boolean success = logesco.mkdir();
                   if(success) System.out.println("Fichier cr�� avec succ�");
                   else System.out.println("Le fichier n'as pas �t� cr��");
              }else
                   System.out.println("Le fichier existe d�ja");
         public static MyClass getRoot() {
              if(logesco == null) {
                   System.out.println("null");
                   logesco = new MyClass(PATH, "logesco");
                   if(!logesco.exists() && !logesco.isDirectory()) {
                        boolean success = logesco.mkdir();
                        if(success) System.out.println("Fichier cr�� avec succ�");
                        else System.out.println("Le fichier n'as pas �t� cr��");
                   }else
                        System.out.println("Le fichier existe d�ja");
              } else {
                   System.out.println("non null");
                   return logesco;
              return null;
         }and the code from MyClass class that extends java.io.File
    public class MyClass extends File {
         private String theme;
         private String description;
         private String type;
         public MyClass(String arg0) {
              super(arg0);
              // TODO Auto-generated constructor stub
         public MyClass(String arg0, String arg1) {
              super(arg0, arg1);
              // TODO Auto-generated constructor stub
         public MyClass(File arg0, String arg1) {
              super(arg0, arg1);
              // TODO Auto-generated constructor stub
         public MyClass(URI arg0) {
              super(arg0);
              // TODO Auto-generated constructor stub
         public MyClass(String aPath, String aName, String aTheme) {
              super(aPath, aName);
              this.theme = aTheme;
         public MyClass(String aPath, String aName,
                   String aTheme, String aDescription) {
              this(aPath, aName, aTheme);
              this.description = aDescription;
         public MyClass(LogescoProject parent, String aName,
                   String aTheme, String aDescription) {
              this(parent, aName);
              this.theme = aTheme;
              this.description = aDescription;
         public String getTheme() {
              return this.theme;
         public String getDescription() {
              return this.description;
         public void setTheme(String aTheme) {
              this.theme = aTheme;
         public void setDescription(String aDescription) {
              this.description = aDescription;
         public void addProject(MyClass aProject) {
              // TODO Auto-generated method stub
              ArrayList<LogescoProject> projects = new ArrayList<MyClass>();
              projects.add(aProject);
         public boolean isProject() {
              return true;
         public MyClass createProject() {
              this.setTheme(theme);
              this.setDescription(description);
              if(!this.exists() && !this.isDirectory()) {
                   boolean success = this.mkdir();
                   if(success) System.out.println("Fichier cr�� avec succ�");
                   else System.out.println("Le fichier n'as pas �t� cr��");
              }else
                   System.out.println("Le fichier existe d�ja");
              return this;
         public void createProject(MyClass newProject) {
              newProject.setTheme(theme);
              newProject.setDescription(description);
              if(!newProject.exists() && !newProject.isDirectory()) {
                   boolean success = newProject.mkdir();
                   if(success) System.out.println("Fichier cr�� avec succ�");
                   else System.out.println("Le fichier n'as pas �t� cr��");
              }else
                   System.out.println("Le fichier existe d�ja");
         public String getType() {
              return this.type;
    }

  • JNI Invocation: open file in Java, write file in CPP

    Hello,
    Warning: I am a dunce, bad CPP code ahead!
    Using JNI invocation, I am trying to read a binary file in Java and write it in CPP.
    Everything compiles and runs without error, but the input and output jpg files are of course different.
    TIA to any help,
    kirst
    (begin ByteMe.java)
    import java.io.*;
    public class ByteMe
        // Returns the contents of the file in a byte array.
        public byte[] getBytesFromFile(String strInfo) throws IOException
            System.out.println("Testing:" + strInfo);
            File file = new File("1.jpg");
            InputStream is = new FileInputStream(file);
            // Get the size of the file
            long length = file.length();
            // Create the byte array to hold the data
            byte[] bytes = new byte[(int)length];
            // Read in the bytes
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length
                   && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
                offset += numRead;
            // Ensure all the bytes have been read in
            if (offset < bytes.length)
                throw new IOException("Could not completely read file "+file.getName());
            // Close the input stream and return bytes
            is.close();
            return bytes;
        public ByteMe()
              //System.out.println("in constructor");
    }(end ByteMe.java)
    (begin ByteMe.cpp)
    #include <stdlib.h>
    #include <string.h>
    #include <jni.h>
    #include <windows.h>
    // for file operations:
    #include <fstream>
    int main( int argc, char *argv[] )
         JNIEnv *env;
         JavaVM *jvm;
         JavaVMInitArgs vm_args;
         JavaVMOption options[5];
         jint res;
         jclass cls;
         jmethodID mid;
         jstring jstr;
         jobject obj_print;
         options[0].optionString = "-Xms4M";
         options[1].optionString = "-Xmx64M";
         options[2].optionString = "-Xss512K";
         options[3].optionString = "-Xoss400K";
         options[4].optionString = "-Djava.class.path=.";
         vm_args.version = JNI_VERSION_1_4;
         vm_args.options = options;
         vm_args.nOptions = 5;
         vm_args.ignoreUnrecognized = JNI_FALSE;
         // Create the Java VM
         res = JNI_CreateJavaVM(&jvm,(void**)&env,&vm_args);
         if (res < 0)
              printf("Can't create Java VM");
              goto destroy;
         cls = env->FindClass("ByteMe");
         if (cls == 0)
              printf("Can't find ByteMe class");
              goto destroy;
         jmethodID id_construct = env->GetMethodID(cls,"<init>","()V");
         jstr = env->NewStringUTF(" from C++\n");
         obj_print = env->NewObject(cls,id_construct);
         // signature obtained using javap -s -p ByteMe
         mid = env->GetMethodID(cls, "getBytesFromFile", "(Ljava/lang/String;)[B");
         if (mid == 0)
              printf("Can't find ByteMe.getBytesFromFile\n");
              goto destroy;
         else
              jbyteArray jbuf = (jbyteArray) env->CallObjectMethod(obj_print,mid,jstr);
              jlong size = jsize(jbuf);
              printf("size is: %d\n", size); // size shown in output is
              std::ofstream out("data.jpg", std::ios::binary);
              out.write ((const char *)jbuf, 100000);     
         destroy:
             if (env->ExceptionOccurred())
                env->ExceptionDescribe();
        jvm->DestroyJavaVM();
    }(end ByteMe.cpp)

    Hello,
    Me again. Well, not such a dunce after all. Here is code that works correctly, and compiles with no errors and no warnings.
    Will much appreciate help with clean-up code.
    TIA,
    kirst
    (begin ByteMe.java)
    import java.io.*;
    public class ByteMe
        public long getFilezize(String strInfo) throws IOException
              // demonstrates String parameter passed from CPP to Java:
              System.out.println("(getFilesize) Hello world" + strInfo);
              File file = new File("1.bmp");
              InputStream is = new FileInputStream(file);
              // Get the size of the file
              long length = file.length();
              is.close();
              return length;
        // Returns the contents of the file in a byte array.
        public byte[] getBytesFromFile(String strInfo) throws IOException
            System.out.println("(getBytesFromFile) Hello world" + strInfo);
            File file = new File("1.bmp");
            InputStream is = new FileInputStream(file);
            // Get the size of the file
            long length = file.length();
            System.out.println("length is: " + String.valueOf(length));
            // Create the byte array to hold the data
            byte[] bytes = new byte[(int)length];
            // Read in the bytes
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0)
                offset += numRead;
            // Ensure all the bytes have been read in
            if (offset < bytes.length)
                throw new IOException("Could not completely read file "+ file.getName());
            // Close the input stream and return bytes
            is.close();
            return bytes;
        public ByteMe()
              //System.out.println("in constructor");
    }(end ByteMe.java)
    (begin ByteMe.cpp)
              Signature obtained with command:
                   "C:\Program Files\Java\jdk1.5.0_15\bin\javap.exe" -s -p ByteMe
                   Compiled from "ByteMe.java"
                   public class ByteMe extends java.lang.Object{
                   public long getFilezize(java.lang.String)   throws java.io.IOException;
                     Signature: (Ljava/lang/String;)J
                   public byte[] getBytesFromFile(java.lang.String)   throws java.io.IOException;
                     Signature: (Ljava/lang/String;)[B
                   public ByteMe();
                     Signature: ()V
         Compiled VC++ 2005 Express, run on Vista
    #include <stdlib.h>
    #include <string.h>
    #include <jni.h>
    // file operations
    #include <fstream>
    int main( int argc, char *argv[] )
         JNIEnv *env;
         JavaVM *jvm;
         JavaVMInitArgs vm_args;
         JavaVMOption options[5];
         jint res;
         jclass cls;
         jmethodID mid;
         jmethodID sizeid;
         jstring jstr;
         jobject obj_print;
         jlong filesize;
         options[0].optionString = "-Xms4M";
         options[1].optionString = "-Xmx64M";
         options[2].optionString = "-Xss512K";
         options[3].optionString = "-Xoss400K";
         options[4].optionString = "-Djava.class.path=.";
         vm_args.version = JNI_VERSION_1_4;
         vm_args.options = options;
         vm_args.nOptions = 5;
         vm_args.ignoreUnrecognized = JNI_FALSE;
         // Create the Java VM
         res = JNI_CreateJavaVM(&jvm,(void**)&env,&vm_args);
         if (res < 0)
              printf("Can't create Java VM");
              goto destroy;
         cls = env->FindClass("ByteMe");
         if (cls == 0)
              printf("Can't find ByteMe class");
              goto destroy;
         jmethodID id_construct = env->GetMethodID(cls,"<init>","()V");
         printf("%s\n",id_construct);
         jstr = env->NewStringUTF(" from C++!\n");
         if (jstr == 0)
              // Normally not useful
              printf("Out of memory (could not instantiate new string jstr)\n");
              goto destroy;
         obj_print = env->NewObject(cls,id_construct);
         //BEGIN BLOCK to get file size
         sizeid = env->GetMethodID(cls, "getFilezize", "(Ljava/lang/String;)J");
         if (sizeid == 0)
              printf("Can't find ByteMe.getFilezize\n");
              goto destroy;
         else
              printf("got here\n");
              filesize =(jlong) env->CallObjectMethod(obj_print,sizeid,jstr);
              printf("got filesize\n");
         // END BLOCK to get file size
         // BEGIN BLOCK to write file
         mid = env->GetMethodID(cls, "getBytesFromFile", "(Ljava/lang/String;)[B");
         if (mid == 0)
              printf("Can't find ByteMe.getBytesFromFile\n");
              goto destroy;
         else
              jbyteArray ret =(jbyteArray) env->CallObjectMethod(obj_print,mid,jstr);
              // Access the bytes:
              jbyte *retdata = env->GetByteArrayElements(ret, NULL);
              // write the file
              std::ofstream out("data.bmp", std::ios::binary);
              //out.write ((const char *)retdata, 921654);
              out.write ((const char *)retdata, (long)filesize);
         // END BLOCK to write file
         destroy:
             if (env->ExceptionOccurred())
                env->ExceptionDescribe();
        jvm->DestroyJavaVM();
    }(end ByteMe.cpp)

  • How to access variables declared in java class file from jsp

    i have a java package which reads values from property file. i have imported the package.classname in jsp file and also i have created an object for the class file like
    classname object=new classname();
    now iam able to access only the methods defined in the class but not the variables. i have defined connection properties in class file.
    in jsp i need to use
    statement=con.createstatement(); but it shows variable not declared.
    con is declared in java class file.
    how to access the variables?
    thanks

    here is the code
    * testbean.java
    * Created on October 31, 2006, 12:14 PM
    package property;
    import java.beans.*;
    import java.io.Serializable;
    public class testbean extends Object implements Serializable {
    public String sampleProperty="test2";
        public String getSampleProperty() {
            return sampleProperty;
    }jsp file
    <%@ page contentType="text/html;charset=windows-1252"%>
    <%@ page import="java.sql.*,java.util.*"%>
    <html>
    <head>
    <title>Schedule Details</title>
    </head>
    <jsp:useBean id="ConProp" class="property.testbean"/>
    <body>
    Messge is : <jsp:getProperty name="msg" property="sampleProperty"/>
    <%
      out.println(ConProp.sampleProperty);
    %>
    </body>
    </html>out.println(ConProp.sampleProperty) prints null value.
    is this the right procedure to access bean variables
    thanks

  • Calling functions of the inner class in .java code file

    Hello,
    I created a .java code file in Visual J#.Net and converted it into
    the application by adding the "public static void main(String args[])"
    function.
    I have created the two classes one extends from Applet, and the other
    extends from Frame. The class which I inherited from the Frame class becomes
    the inner class of the class extended from the Applet. Now How do I
    call the functions of the class extended from Frame class - MenuBarFrame
    class. the outline code is
    public class menu_show extends Applet
    ------init , paint action function---------
    public class MenuBarFrame extends Frame
    paint,action function for Menu
    public static void main(String args[])
    applet class instance is created
    instance of frame is created
    Menu , MenuBar, MenuItem instance is created
    and all these objects added
    I have Created MenuBarFrame class instance as
    Object x= new menu_show().new MenuBarFrame
    ????? How to call the functions such as action of MenuBarFrame class - what
    should be its parameters??????
    }

    Here's how I would do it:
    interface Operation {
        public int op(int y);
    class X {
        private int x;
        public X(int x) {
            this.x = x;
        private class Y implements Operation {
            public int op(int y) {
                return x+y;
        public Operation createOperation() {
            return new Y();
        public static void main(String[] args) {
            X app = new X(17);
            Operation f = app.createOperation();
            System.out.println(f.op(-11));
    }Your code, however, has some serious "issues". You typically don't
    instantiate an applet class -- that's the job of the applet viewer or Java plugin
    your browser is using. If you instantiate the applet directly, you're going
    to have to supply it an AppletStub. Do you really want to go that way?
    Again, use an applet viewer or browser, or better yet, why write applets at all?

  • Java.io.File extension proposal

    Hi, i have made an extension to java.io.File that right now lets you find out free disk space, used disk space and all mounted volumes.
    I currently have code for linux only and i'm looking for help porting it to win32.
    I put up a project page on http://mog.se/mogio.html
    I'm aware of projects like JConfig and i'm not interested in it because of their license and their totally different API. se.mog.io.File extends File to work just like a normal java.io.File with some additional methods, in the spirit of java.io.File. :)
    Any help in coding or feedback is appreciated, be it negative or positive. :)
    /mog

    listMounts() is intended to be like listRoots() but
    show mounted volumes below the root.I thought about this too, but the mounts themselves wouldn't really be `below' the root as one could mount anywhere in the Unix fs tree. Now wouldn't the mounts actually be the roots in Winblows?
    What would be nice would be some metric given any given java.io.File directory, such as I may know that the directory has a metric that lets me know the quality of the disk such as a good SCSI array for persistent storage vs. a single IDE for a scratch or temp dir.
    I'm not aware of AS/400 or any anti-OS pro-JVM devices
    but would java.io.File be applicable there anyway?File would be of course applicable for the IFS on AS/400, but it's been a LONG time (read deploying on 1.1 V4R?) since I've used the 400 and I don't have detailed knowledge on storage management there, so I may need to defer to someone on that architecture to know about mounts, etc.
    There is however a really small group of people who feel that all storage should be secondary or auxillary storage (I'm partially one of them) and when you need to access data, you peek at a memory location (to which of course you would have access) or pointer|reference|et al. The OS is then responsible for intelligently paging that data in/out of primary memory for access, like a super-mega-MM, or conversely just read from the secondary itself, either way the VM wouldn't care. We're a ways away from an OS/JVM combo like this though and I feel it will be a long time until we get rid of the traditional thought process of filesystems.

  • How to Extend Java class in UI Module

    Hi All,
    I am trying to make z for one of the java file GenericSearchDynamicContent.java in the standard package com.sap.wec.app.common.module.catalog.ui.utils. Can anyone please let me know what are steps do i need to follow to extend the same java file in our customer namespace and make use of it.
    Thanks in Advance.
    Regards,
    Rahul.

    Hi Rahul,
    It's upto you whether you want to keep seprate packages for custom changes (then create your own package and keep all the Z class under this) or create a Z_GenericSearchDynamicContent.java and extend this class by GenericSearchDynamicContent.java.
    After doing this you can make your custom changes accordingly and you have to also make the changes in *config.xml (replace this entry GenericSearchDynamicContent by Z_GenericSearchDynamicContent.java.) files as mapping is done there.
    Could you please let me know if you need any further information.
    Thanks,
    Hamendra

  • XML to Java source files

    Hi,
    I need to create classes and interfaces for certain elements in my node.xml ( along with a node.dtd).
    In my node.xml I have the following element:
    <exception name="XXNotLockedException">
    <description>The xxxx to be tested was not in administrative state LOCKED.</description>
    <exceptionParameter name="message">
    <dataType>
    <string/>
    </dataType>
    </exceptionParameter>
    </exception>
    from this I want to generate a java source file like below.
    Is it a possible and good way to do it? Or is it the old SAX with events that shall be used?
    I have managed to generate java files but they are only the default ones.
    All help appreciated from more experienced programmers.
    //Mikael
    Source file
    package se.company.xxx.bcm.iface;
    public class XXNotLockedException
    extends se.company.xxframework.XXAccessException
    * Constructor
    public XXNotLockedException()
    super("XXNotLocked");

    I would say using XSLT would be easier to understand than a SAX events program. And more flexible, too, if your requirements changed.

  • JSP Tag -- Including a JSP fragment in a Java Tag file

    Hi all,
    I have a query regarding JSP Tag file authoring by extending the TagSupport class. I would like to know if it is possible to include a JSP file fragment inside a Java file somehow.
    Specifically, I have created a simple template tag, which adds a header and footer template to the resulting HTML page.
    <bc:template>
    Hello World!
    </bc:template>produces for example
    <html><body>
    Hello World!
    </body></html>Now I have two JSP fragment files (head.jspf and foot.jspf), and I want to do do something like
    public class HtmlTemplateTag extends TagSupport implements TryCatchFinally {
      public int doStartTag() {
        // somehow include head.jspf
        return EVAL_BODY_INCLUDE;
      public void doFinally() {
        // somehow include foot.jspf
    }Which means, I want to execute had.jspf and foot.jspf from the Java class file. I am not sure if it is even possible. If anyone can help me with this, it would be greatly appreciated.
    thanks
    nilesh

    Your intention is to put a header/footer on pages in your web application?
    There is another way to do it - specify prelude/coda jsp fragments in web.xml
    Something like the following:
    <jsp-config>
      <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <include-prelude>/WEB-INF/jspf/head.jspf</include-prelude>
        <include-coda>/WEB-INF/jspf/foot.jspf</include-coda>
      </jsp-property-group>
    <jsp-config>

  • Java.io.File not found in JDK 1.4

    why the java.io.file is deprecated.
    Frans

    [fthamura],
    why the java.io.file is deprecated.Probably because in J2SE 1.4, the New I/O package java.nio package provides scalable I/O operations for files. Through the File channels, a programmer will be able to provide memory-mapped buffers, improved file locking mechanism and faster I/O transfers with the new API package.
    FransHTH.
    Allen Lai
    Developer Technical Support
    SUN Microsystems
    http://www.sun.com/developers/support/

  • Getting all the members (variables, methods AND method bodies) of a java source file

    For a project I want to programmatically get access to the members of java source file (member variables, methods etc) as well as to the source code of those members. My question is what is the best method for this? So far I have found the following methods:
    Use AST's provided by the Java Source API and Java Tree API, as discussed in the following posts:
    http://today.java.net/pub/a/today/2008/04/10/source-code-analysis-using-java-6-compiler-apis.html
    http://weblogs.java.net/blog/timboudreau/archive/2008/02/see_java_code_t.html
    http://netbeans.dzone.com/announcements/new-class-visualization-module
    This has the disadvantage that the classes actually have to be compilable. When I look at the Netbeans Navigator view however, it provides me with a nicely formatted UI list, regardless of the "compilable" state of the class.
    Thus I started looking at how to do this... The answer appears to be through the use of tools such as JavaCC: https://javacc.dev.java.net/
    ANTLR: http://www.antlr.org/
    which are lexers and parsers of source code. However, since the Navigator panel already does this, couldn't I use part of this code to get me the list of variables and methods in a source file? Does the Navigator API help in this regard?
    Another route seems to be through tools such as
    BeautyJ: http://beautyj.berlios.de/
    which run on top of JavaCC if I am correct, and which has the ability to provide a clean view on your java code (or an XML view). However, BeautyJ does not seem to be too actively developed, and is only j2se1.4 compatible.
    I hope someone can shed a light on the best way to go about what I want to achieve. Somebody already doing this?
    (I crossposted on the Netbeans forums too, hope this is OK...)

    I'm currently developing a LaTeX editor(MDI) and I do the same thing, but I don't know what exactly do you need.

  • 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?

  • How to convert a .jsp to a .java/.class file for use in peoplesoft

    Hi java/jsp experts,
    I want to convert a .jsp to a .java/.class file. is there a tool available, please let me know if you have any pointers....
    or can i do it manually:
    these are a few lines that the .jsp contains, and i would like to translate this to be in .java/.class format:
    <%@ page import="sun.misc.BASE64Encoder, javax.crypto., javax.crypto.spec."%>
    <%@ page import="java.util.StringTokenizer" %>
    <%@ page import="java.util.Map" %>
    <%!
    sb.append("<input type=\"hidden\" name=\"orderPage_serialNumber\" value=\"");
    sb.append(serialNumber);
    sb.append("\">\n");
    return sb.toString();
    %>
    how can i translate the above import statements and html elements from jsp to java, please let me know.
    Once i have the .java file created from the .jsp, I will compile .java to create the .class file and invoke the .class in peoplecode by using java apis available in peopletools.
    Thanks in advance.

    Is there a way convert a binary .exe file( compiled by
    another compiler) into Java .class/.jar file ? Anyone
    know of a free program that can do this?It's not possible. There are many decompilers and disassemblers for Java but nothing will take you from ANY binary to Java source. It would be the end of computing as we know it and the beginning of a new era -:)

  • How to convert dll to a java class file?

    Hi folks:
    I have some DLLs in VB and C++ and I wanna to convert them to a java class file. Does anybody know if exist a sw or easy way to do it?
    thanks
    Autair

    Well, I believe you could write JNI to call the functions in the DLLs, although I wouldn't recommend it. (You'd have a non-portable, fragile result.)

Maybe you are looking for