Creating a new file...


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: Creating a new file...

  1. #1
    Join Date
    Mar 2003
    Posts
    834

    Creating a new file...

    Does anyone know how to create a file in a directory where the directory has not yet been created?

    i.e. dir1/dir2/dir3/myFile.txt (where dir1, dir2 and dir3 are created if they don't already exist).

    I wrote this little app for testing:
    Code:
    import java.io.*;
    
    public class Writing {
            public static void main(String[] args) throws IOException {
                    File target = new File(args[0]);
                    if (!target.exists()) {
                            boolean success = target.createNewFile();
                            System.out.println("Attempted to create new file..." + success);
                    }
                    PrintStream ps = new PrintStream(new FileOutputStream(target));
                    ps.println("Hello");
            }
    }
    ArchAngel.
    O:-)

  2. #2
    Join Date
    Mar 2003
    Posts
    834

    One step better...

    Not quite automatic, but closer...
    Code:
    import java.io.*;
    
    public class Writing {
            public static void main(String[] args) throws IOException {
                    File dir = new File(args[0]);
                    File file = new File(dir, args[1]);
    
                    boolean success;
                    success = dir.mkdirs();
                    System.out.println("Attempted to create dirs..." + success);
                    success = file.createNewFile();
                    System.out.println("Attempted to create new file..." + success);
    
                    PrintStream ps = new PrintStream(new FileOutputStream(file));
                    ps.println("Hello");
            }
    }
    ArchAngel.
    O:-)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center