Results 1 to 5 of 5

Thread: CREATE a file...

  1. #1

    Thread Starter
    PowerPoster rjlohan's Avatar
    Join Date
    Sep 2001
    Location
    Sydney, Australia
    Posts
    3,205

    CREATE a file...

    Does Java actually have support for file creation. I've not been having a good time with I/O when a file doesn't exist...
    -----------------------------------------
    -RJ
    [email protected]
    -----------------------------------------

  2. #2
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418
    This might help you out. Be sure to import java.io.* or java.io.File into your app though.
    Code:
    public static void create(){
         // if directory already exists mkdir() will just return false and the directory 
         // will not be overwritten.           
        try{                   
          File dir = new File("C:\\InitialDirectory");
           dir.mkdir();
            File f = new File("\\Justatextfile.txt");
             f.createNewFile();
              File dest = new File("C:\\InitialDirectory\\" + f.getName());  
               f.renameTo(dest);
         }catch(IOException e){System.err.println(e);}
        }

  3. #3

    Thread Starter
    PowerPoster rjlohan's Avatar
    Join Date
    Sep 2001
    Location
    Sydney, Australia
    Posts
    3,205
    Ok. Easy.
    I just kept getting the impression that the
    File f = new File("\\Justatextfile.txt");
    line was raising a FileNotFound exception...
    -----------------------------------------
    -RJ
    [email protected]
    -----------------------------------------

  4. #4
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418
    The file dosn't actually have to be there in order to create a new file object. Certian streams will throw a FileNotFoundException if the if a nonexistent file is passed in as an arguement. Some classes like RandomAccessFile will throw a FileNotFoundException when in 'r' mode and the file does not exist. But will create a file if in 'rw'.

  5. #5
    Hyperactive Member CaptainPinko's Avatar
    Join Date
    Jan 2001
    Location
    London, Ontario, Canada
    Posts
    332
    i think this works:

    Code:
    import java.io.*;
    
    PrintWriter file = new Printwriter ( new OutputSteamWriter ( new FileOutputStream ("asdf.txt")));
    some of those class names amybe wrong but that close enuff 4 u 2 fig it out
    "There are only two things that are infinite. The universe and human stupidity... and the universe I'm not sure about." - Einstein

    If you are programming in Java use www.NetBeans.org

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width