File constructor

I'm trying to search in directories on my local machine, and in order to do so I'm trying to use the following code:
File myfile = new File("c:/temp");
When I compile this line of code I get following error:
Wrong number of arguments in constructor.
The only code the compiler (jdk1.3.1) will accept is File myfile = new File();, but how can I use that to specify a certain folder or file?
I get the same error message when I try to compile the following code, which I copied from the sun web site:
import java.io.*;
public class Copy {
public static void main(String[] args) throws IOException {
     File inputFile = new File("input.txt");
     File outputFile = new File("output.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
Thanks
Jens

there shouldn't be anything wrong with your code
The File-class has three constructors:
File(String pathname);
File(String parent, String child);
File(File parent, String child);
no no-argument constructor

Similar Messages

  • Query on File() constructor parameter

    I have a query on the File(String pathname) constructor.
    Could anyone advise me why its parameter is the pathname? Is the pathname has included the file's name?
    String mypahtname = "c:\\folder\\";
    String myfilename = "abc.txt";
    String mystring = mypathname + myfilename;
    File myfile = new File(mystring);The above is working. However, the parameter is not the pathname. Why is it working?

    A File object in Java may point to either an actual file, or a directory. So the final member of the path String parameter may be either a file or directory.
    Read the first paragraph here
    http://java.sun.com/javase/6/docs/api/java/io/File.html

  • MySql jar file constructor

    Hello,
    I am developing web application using JSP and MySql. I am using netBeans 4.1 as IDE.
    To connect with database I have included jar file "mysql-connector-java-3.1.10-bin.jar" to Libraries folder of my project in netBeans. This jar file contains many classes, one which I want to use is com.mysql.jdbc.Blob.
    In my jsp file I want to call Blob(byte[]) constructor. For that I am doing :
    com.mysql.jdbc.Blob myBlob = new com.mysql.jdbc.Blob(dataBytes);
    Where dataBytes is an initialized array of bytes.
    When I compile my jsp file I get error "can not find symbol". It says it is not able to find constructor.
    So where I am making mistake. To resolve this problem which actions should I take??
    Jahnvi

    Hello,
    I am developing web application using JSP and MySql. I am using netBeans 4.1 as IDE.
    To connect with database I have included jar file "mysql-connector-java-3.1.10-bin.jar" to Libraries folder of my project in netBeans. This jar file contains many classes, one which I want to use is com.mysql.jdbc.Blob.
    In my jsp file I want to call Blob(byte[]) constructor. For that I am doing :
    com.mysql.jdbc.Blob myBlob = new com.mysql.jdbc.Blob(dataBytes);
    Where dataBytes is an initialized array of bytes.
    When I compile my jsp file I get error "can not find symbol". It says it is not able to find constructor.
    So where I am making mistake. To resolve this problem which actions should I take??
    Jahnvi

  • Java.io.File constructor - pathnames on tomcat

    Hi,
    I am trying to implement a file upload feature on my website using Flash 8 and jakarta commons FileUpload.
    I'm running into problems with the java.io.File class. I want to save uploaded files in a folder not relative to the calling page's context.
    When I use the following three lines, the files get saved correctly (in an "/uploads" folder in the current context):
    File fullFile = new File(item.getName());
    File savedFile = new File(getServletContext().getRealPath("/uploads"), fullFile.getName());
    item.write(savedFile);
    However, when I use the following instead of the second line, I get an http 500 error:
    File savedFile = new File("/absolute/path/to/another/context/uploads", fullFile.getName());
    What's strange is when I put in a println, I see that
    getServletContext().getRealPath("/uploads") = /usr/local/tomcat/webapps/mywebapp/uploads
    However, when I substitute the string in the new File(String parent, String child) method, I also get a http 500 error:
    File savedFile = new File("/usr/local/tomcat/webapps/mywebapp/uploads", fullFile.getName());
    This is the stack trace:
    2006-02-03 12:12:05 StandardWrapperValve[jsp]: Servlet.service() for servlet jsp
    threw exception
    org.apache.jasper.JasperException: /upload.jsp(11,2) Unterminated <% tag
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorH
    andler.java:39)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.j
    ava:409)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.j
    ava:134)
    at org.apache.jasper.compiler.Parser.parseScriptlet(Parser.java:796)
    Am I understanding the methods incorrectly?
    Any help would be greatly appreciated! I am completely stuck
    Thank you.

    May be the security manager is not allowing to save files in the folders outside your context.
    Put your code within a try catch block and see it there is any exception and if yes print the stack trace and look whats in it

  • File constructor and TimerTask

    Hello.
    I have two questions.
    One is I need to create a file with the name of an image.
    For example I have an image in the path classes/Ventanas/router.png.
    This path is created when the classes are compiled.
    I did the same in other class with the path
    ImageIcon icononodo = new ImageIcon(Ventanas.PantallaRedJGraph.class.getResource("router.png"))
    But when I try to do it whit File it doesn�t work.
    File f = new File(Ventanas.PantallaRedJGraph.class.getResource("router.png").getFile());
    Does anybody know anything about it?
    And the other question is I have a class that extends Timer.
    Inside this class I have a TimerTask
    public class Sondear extends Timer{
    String ipasondear;
    public ConectorInterfaz conector = ConectorInterfaz.getInstancia();
    final Runnable sondeo = new Runnable(){
         public void run(){
         //The code     
         }//run
    };//sondeo
    TimerTask repetirsondeo = new TimerTask(){
         public void run(){
         EventQueue.invokeLater(sondeo);
         }//run
    };//repetirsondeo
    public void sondeando(String ip){
         this.ipasondear = ip;
    this.schedule(repetirsondeo, 0, 45000);
    }//sondeando
    I call this class from another class with the instruction.
    for( //all the IP adresses){
    Sondear s = new Sondear();
    s.sondeando(//The ip);
    My question is how can I stop this TimerTask for a period of time and call another time this class to pass another IP adresses?
    I will be very grateful if somebody helps me.
    Thank you very much and sorry for my english.

    paulcw wrote: > Probably the file doesn't exist, at least not in the way you think it does and/or with the name you get from URL.getFile().
    Why are you doing it that way? Is the file a jar file? If so you should use getResourceAsStream (and no File objects at all).
    Also you should provide more details. What do you mean "it doesn't work"? Do you get an exception? If so you should post it with your question.
    >>
    Perhaps I didn`t explain it well. SorryI don�t get an exception. The image in my application doesn�t appear.
    At first I have all .java files in a directory called src. And I have another directory with all my images.
    When I execute the application I send the .class files to a directory called classes and the images to a directory called Ventanas.
    I don�t know exactly how it is used the instruction
    new ImageIcon(Ventanas.PantallaRedJGraph.class.getResource("imagename"));But in a previous application it works, so the image appears in the application.
    You told me that how I did it this way.
    I don�t know a lot about programming, so if there is a better way to do this with a File I will be very grateful if you say it to me.
    paulcw wrote: > That seems unnecessary. Just instantiate a Timer and use it.
    Your code in general seems unnecessarily complicated.
    I'd suggest canceling that task, and then scheduling a new one later if you need it to run again. If the task contains state that needs to be preserved across the times that it runs, then put that state in a different object and pass that object to multiple TimerTask wrappers.
    >
    I have an application that sends ping to another computers and routers to see if there are connected to the network.
    When the user press a button to scan the network, the application begins to look for devices and when it draws the devices connected I need that it begins to sends the ping instructions.
    When the Scan button is pressed I don�t know if it is the first time the user press it or not.
    What I want is that when the application is scanning the network I need to stop the Timer and restart it when the network is scanned. I need to stop all the Timers I send for all the IP addresses.
    I also think that my code is a bit complicated but I don�t know another way to do it.
    How can I see if an instance of this class is created?
    I have a trouble in my mind.
    I hope this time my explanation has been easy to understand. My English is a bit poor .
    Thank you, thank you very much.

  • File constructor and unicode filename issue

    I have issues with unicode filename.
    I need to create a File object from unicode file name "&#1070;&#1075;&#1072;.mp3" in order to use it in the code.
    File in=new File("&#1070;&#1075;&#1072;.mp3")
    AudioFile f = AudioFileIO.read(in);
    Tag tag = f.getTag();
    Anybody knows how to deal with a file or directory that is named using Unicode characters?

    1) Have you tried just reading the file as a file using a FileInputStream?
    2) What operating system?
    3) What Java version?
    4) What are the \uxxxx values of some of the problem characters?
    Edit: I have just run        String filename =  System.getProperty("user.home") + "/\u1070\u1075\u1072.mp3";
           File file = new File(filename);
           OutputStream os = new FileOutputStream(file);
           os.write("Hello World".getBytes("utf-8"));
           os.close();
           DataInputStream dis = new DataInputStream(new FileInputStream(file));
           byte[] buffer = new byte[(int)file.length()];
           dis.readFully(buffer);
           dis.close();
           System.out.println(new String(buffer,"utf-8"));on Unbuntu 7.10 using JRE/JDK1.6.0_3
    without any problems other than not being able to see the \u1070\u1075\u1072 in my console because I don't have fonts installed for displaying them.
    Edited by: sabre150 on Dec 28, 2007 8:52 AM
    Further edit: It also runs on Windows XP using 1.6.0_03 .
    Edited by: sabre150 on Dec 28, 2007 9:00 AM
    I don't think the file is located where you think it is!
    Edited by: sabre150 on Dec 28, 2007 9:02 AM

  • How to write data into a file

    Hi
    I want to write data from a string into a file. I am created a directory and a .doc file . But when i write this data from a string into .doc file , its give an error : File not found exception
    But, when i check in my directory, a file is created with blank.
    My code is:
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    class createFile {
         public static void main(String[] args) {
    try {
         String mss = "This is for dedo";
         FileInputStream fis;
         FileOutputStream fos;
    File file = new File("C:\\JD\\m4.rtf");
    // Create file if it does not exist
    boolean success = file.createNewFile();
         success = true;
    if (success) {
                   System.out.println("suc");     
                   fis = new FileInputStream(mss);
                   System.out.println(fis);
              fos = new FileOutputStream(file);
              int c;
                   while ((c = fis.read()) != -1) {
         fos.write(c);
                   System.out.println("mss");
              fis.close();
              fos.close();
         System.out.println("created");
    // File did not exist and was created
    } else {
    // File already exists
    } catch (IOException e) {
         System.out.println(e);
    regards
    madhu

    InputStream inputStream = new ByteArrayInputStream(mss.getBytes());Use this to push into the file>
    Ummm.... no. InputStreams are for reading, not for writing.
    Anyway, OP, you're making a mistake. You're trying to open a stream to a file called "This is for dedo". Use FileOutputStream(File file) constructor or FileOutputStream(String pathToFile). You can then wrap that stream with a PrintWriter or whatever you need.

  • File Not Found exception.Am i missing anything?

    I have created a file called CI.xml in an eclipse folder which exists
    I am getting the message: The system cannot find the file
    my code is
    private static final String XML_TEMPLATE_FOLDER ="xml/template"
    String fileFolder = getTemplateFolder();
    File file = new File(fileFolder+"CI.xml");
    private String getTemplateFolder(){
    return XML_TEMPLATE_FOLDER;
    }If I save this file on c:\ and pass it to the file api,it works.
    am i overlooking anything?
    please guide

    masijade. wrote:
    phdk wrote:
    try: xml\\template
    or use File.separatorNo need. In the File constructors "/" is always valid, regardless of the OS. (Now Runtime.exec() is another story, but that's not what we're talking about here.)I've noticed that "/" works on Windoze, but I can't find the documentation. The closest is this, in the [File API:|http://java.sun.com/javase/6/docs/api/java/io/File.html]
    <quote>
    The conversion of a pathname string to or from an abstract pathname is inherently system-dependent. When an abstract pathname is converted into a pathname string, each name is separated from the next by a single copy of the default separator character. The default name-separator character is defined by the system property file.separator, and is made available in the public static fields separator and separatorChar of this class. When a pathname string is converted into an abstract pathname, the names within it may be separated by the default name-separator character or by any other name-separator character that is supported by the underlying system. [Ed.: hmmm]
    </quote>
    So I don't know if I can take _"/" is always valid_ as vaild, unless there's better documentation for it.

  • How to get the Real Path of a file which is accessed  by URL?

    iam using tomcat6.0.
    I have a file xyz.xml at the top of the webapplication HFUSE which i can able to access by URL
    http://localhost:8080/HFUSE/xyz.xml
    My problem is how to get the realpath of the file "xyz.xml" for reading and writing purposes.
    I tried various things but i could not able to successfully solved the problem?
    1) File f = new File("/xyz.xml");
    print(f.getAbsolutePath()) ============== it is not fetching the file @ http://localhost:8080/HFUSE/xyz.xml rather it is creating a file
    at the root of the drive where eclipse is running.
    2) File f = new File("xyz.xml");============> this is also not working , it is creating the file xyz.xml in the eclipse directory ..................
    Can anyone please guide on this problem?

    RevertInIslam wrote:
    If you want your context root(i.e HFUSE)
    use this:
    request.getContextPath() //where request is HttpServletRequest object to get the needful path.
    e.g:
    File f = new File(request.getContextPath()+"/xyz.xml");//it will create the file inside HFUSE.
    Hope this helps.
    Regards
    BWrong. The File constructor expects an absolute filesystem path. The HttpServletRequest#getContextPath() doesn't return the absolute filesystem path, it only returns the relative path from the current context root. Use ServletContext#getRealPath() instead, it returns the absolute filesystem path for the given relative path from the current context root.
    File file = new File(servletContext.getRealPath("/"), "xyz.xml");

  • [File] Problem while creating files with long pathnames

    Hello everybody
    I'm trying to create File objects corresponding to physical files. These files have very long pathnames because they are located in directories tree with large depth. So, my pathname conatins a lot of directories plus the name of the file itself.
    It seems, that there is a limitation in the length of the pathname that I pass to the File constructor because files with small pathnames are OK bu the ones with very large pathnames cannot be created.
    I tried the different File constructors (File(String pathname) and File(File parent, String childname)) but it still does not work. Even if the second constructor is a little bit better as it succeeds on files where the first constructor failed. But still, it's not enough.
    Please Help!
    Thank you
    Hugo

    RESOLVED!
    The problem was from the OS itself (Windows XP) which accepts at most 255 characters long path names.

  • File Paths on windows and unix

    Hi
    I believe I read that when specifiying file paths in java, this is one aspect which is not platform independent. So if you develop something on windows which uses file paths if you wish to run it on unix you will need to change the syntax pertaining to the path. Is this correct?
    Cheers

    Well, generally file paths on unix and windows are very differently arranged, so it's actually fairly unlikely you'd want the same paths. Genarally files are either resources, best accessed with getResource/getResourceAsStream or they ought to be variable, perhaps stored in configuration (it's well worth getting to know java.util.prefs.Preferences).
    And I usually find that if I'm dealing with a directory heirarchy relative to some base directory the two parameter File constructor is cleaner than mucking about with path separators.

  • Why can't I read any of my resources in a jar file?

    For an application I was developing, I wanted to create a Binary File using the following code:
    DataInputStream in = null;
            try {
                File file = new File(name);
                in = new DataInputStream(
                        new BufferedInputStream(
                            new FileInputStream(file)));
            } catch (FileNotFoundException e) {
                System.out.println("Non-existential File.");
                System.exit(0);
    }I am using Netbeans 6.5.1., and it groups my projects so that there are folders for build, src, dist, nbproject inside the project folder. The application that I am developing is a graphics demo that requires the use of several text files to represent the maps, so I wanted to read them using a FileInputStream.
    I kept this file, "islandmap.txt", in the src folder in my project. In the method above, I coded my program so that the "name" would be "src\islandmap.txt", and it read from the file perfectly. However, I needed to compile it to a Jar file too. After doing that, the program no longer functioned. I remembered when I used a tutorial long ago that used
    URL url = getClass().getClassLoader().getResource(fileName) ... in order to get the directory of the files. That made sense, because a person who is running the program via Java Webstart or a Jar Executable would definitely not have the parts of the program located in the same directory, so the code is used to find where the java program is. However, I realized something...
    File file = new File( - constructor - )There are four constructors for files, and I only think I could use two. The first is using a string, like I have done before with "src\islandmap.txt." Now, the URL url = getClass().getClassLoader().getResource(fileName) part, it was used before to locate a URL in order to open a buffered image. The constructor for File does not support URLs, but instead supports URIs.I tried converting between the two, changing a URL into a string, and producing a URI from the string. But it did not work, giving me an error that URI was not hierarchical. And that's when I realized that they were certainly not interchangable.
    More specifically, here is my code as of now:
    public boolean loadMap(String mapName) {
            String path = "src/islandmap.txt";   //This is where the map files are stored
            mapName = getClass().getClassLoader().getResource(path).getPath(); //getPath changes the URL into a String
            DataInputStream in = null;
            try {
                File file = new File(mapName);
                in = new DataInputStream(
                        new BufferedInputStream(
                            new FileInputStream(file)));
                 //code to actually read from the file goes here
            } catch (FileNotFoundException e) {
                System.out.println("Non-existential File.");
                System.exit(0);
            } finally {
                 //close in
    }So that is my problem now. I am stuck. For my purposes, I basically must use a stored text file within my jar, but I don't know how to read it. It distresses me that normally, I already know how to open images that are located inside my src folder using URLs, but not any other file requiring a File class to be wrapped within a Buffered Writer/Reader. Could somebody please assist me with this, or suggest an alternative that would also fall under my conditions? I would appreciate it so much. Thank you.
    Edited by: celestialsalt on Dec 6, 2009 5:29 PM
    Edited by: celestialsalt on Dec 6, 2009 5:49 PM

    Start with
    URL url = getClass().getClassLoader().getResource(fileName)Then observe that URL has a [openStream()|http://java.sun.com/javase/6/docs/api/java/net/URL.html#openStream()] method that will give you an InputStream. Since you are reading text you might want to create an InputStreamReader from which you can do your reading much like you used the FileReader before when you were working with a File.
    Class also has a [getResourceAsStream()|http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)] which combines the first two steps into one. Ie use getResource() as you mentioned when you want to get a URL that some other class will use to read (eg an image) or use getResourceAsStream() when you are going to do the reading yourself.

  • How to retreive an xml file from a remote computer?

    Hello,
    I have an xml file which is sitting at this location:
    main-uni1\c$\Companies\OutGoing\MonyReports\test.xml
    My question is how can I create new File which will contain this xml file for parsing? The File constructor doesn't receive these notations.

    Hi,
    I tried the following
    try{
                   File f=new File("
    "+"
    <remote system name>
    c#
    test.txt");
                   int size=(int)f.length();
                   System.out.println(""+size);
              }catch(Exception e){
                   System.out.println(e.toString());
    I recieved a 0 with the web dynpro while i recieved the file size using simple java code.
    I also tried writing something into the file in web dynpro and recievd a fileNotfound exception due to unknown username or bad password.
    Check out the code and do let me know about the result
    Regards
    Shyam R

  • Remote file transter to windows and unix scp?

    Hi,
    I have to develop a new software component for a change managment. This component runs on a application server (based on windows 2003) and must copy or excute files on unix and windows. For unix copy I use ftp class of Ant. For windows (from one domain to another). I would like to use Scp but I do not know how I have to build my connect string for an windows domain.
    I try to test a connection und get a error �connection refused�.
    try {
    scp = new Scp();
    Project project = new Project();
    scp.setFile("C:/temp/test.txt");
    scp.setTrust(true);
    scp.setTodir("test:[email protected]:/D:/temp/");
    scp.setProject(project);
    scp.execute();
    catch (Exception exception) {
    exception.printStackTrace();
    om.jcraft.jsch.JSchException: Session.connect: java.net.ConnectException: Connection refused: connect      at org.apache.tools.ant.taskdefs.optional.ssh.Scp.execute(Scp.java:187)      at com.hannover_re.ct.test.TestCommandsExecutor.testCopy2(TestCommandsExecutor.java:310)      at com.hannover_re.ct.test.TestCommandsExecutor.main(TestCommandsExecutor.java:41) Caused by: com.jcraft.jsch.JSchException: Session.connect: java.net.ConnectException: Connection refused: connect      at com.jcraft.jsch.Session.connect(Unknown Source)      at com.jcraft.jsch.Session.connect(Unknown Source)      at org.apache.tools.ant.taskdefs.optional.ssh.SSHBase.openSession(SSHBase.java:180)      at org.apache.tools.ant.taskdefs.optional.ssh.Scp.upload(Scp.java:249)      at org.apache.tools.ant.taskdefs.optional.ssh.Scp.execute(Scp.java:176)      ...
    2 more --- Nested Exception --- com.jcraft.jsch.JSchException: Session.connect: java.net.ConnectException: Connection refused: connect      at com.jcraft.jsch.Session.connect(Unknown Source)      at com.jcraft.jsch.Session.connect(Unknown Source)      at org.apache.tools.ant.taskdefs.optional.ssh.SSHBase.openSession(SSHBase.java:180)      at org.apache.tools.ant.taskdefs.optional.ssh.Scp.upload(Scp.java:249)      at org.apache.tools.ant.taskdefs.optional.ssh.Scp.execute(Scp.java:176)      at com.hannover_re.ct.test.TestCommandsExecutor.testCopy2(TestCommandsExecutor.java:310)      at com.hannover_re.ct.test.TestCommandsExecutor.main(TestCommandsExecutor.java:41) Process exited with exit code 0.
    Is it the right way to use SCP? How can I realize a solution for my project?
    Please help :-)
    Thank you for your help.

    Well, generally file paths on unix and windows are very differently arranged, so it's actually fairly unlikely you'd want the same paths. Genarally files are either resources, best accessed with getResource/getResourceAsStream or they ought to be variable, perhaps stored in configuration (it's well worth getting to know java.util.prefs.Preferences).
    And I usually find that if I'm dealing with a directory heirarchy relative to some base directory the two parameter File constructor is cleaner than mucking about with path separators.

  • List of files in directory

    I need to access a list of files in a directory. The files are .js scripts that I want to dynamically insert into a page with JSP. The problem is that at my company these .js scripts will often be added/removed and it would simplify the process to just look at what's in the directory and pick out the appropriate .js that are available.
    My directory structure is arranged something like this:
    ./src/jsp for the jsp pages
    and
    ./conf/somescripts for the .js scripts.
    I tried accessing it with getClass().getResource() to get the URL, and I also tried File(relativePathToSomescripts) but without much success - tends to get nulls in return. I'm not too experienced with JSP, but I'm guessing the relative paths change once Tomcat compiles them. So what would be a reliable way to access the list of files in the script directory?

    The File constructor only accepts absolute URI's. You can get the absolute URI for the relative URI using ServletContext#getRealPath().
    String absolutePath = servletContext.getRealPath(relativePath);

Maybe you are looking for

  • Acrobat File Not Found After Printing Web Page

    Here is my problem: I am trying to print a web page from our intranet but once the process is complete, a log file opens saying: "The system cannot find the file" and then it lists the file I just tried to create. The page is basic HTML with a small

  • Date Format Issue in Session

    DECLARE err_mesg_out          NUMBER(1):=0; x     DATE; y     VARCHAR2(50) := Null; z     DATE; BEGIN select scheduled_date into x from CONTRACT_SCHEDULED_FULFILLMENT where CONTRACT_ID=94875672 and fulfillment_type_id=9; dbms_output.put_line('x ='||x

  • Abap knowledge for SD consultant

    Dear Friends,                    Iam a SD consultant, I want to know upto what extent Abap knowledge is required by a SD consultant. Please tell me on what topics we need have knowledge to be compitetive in market. I believe companies are looking for

  • Reading electronic identity cards in a windows store app project

    In a windows store app project, i've been ask to implement a way to read the information on a Electronic Identity card such as this is there any API i can use on a windows Store App project to achieve this? can't seem to find anything of sorts

  • K790i - Problem in accessing Application and Games Folder

    Hi I am not able to open the Application and Games folder on my Sony Ericsson K790i Mobile Phone. It gives me an exception "Operation Failed". Please advise, what needs to be done.