DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 2 of 2
  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:-)

Bookmarks

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


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links