Create a file: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
Line 21: Line 21:
}
}
}
}

public static void test(String type, String filename) {
public static void test(String type, String filename) {
System.out.println("The following " + type + " called " + filename +
System.out.println("The following " + type + " called " + filename +
Line 27: Line 26:
);
);
}
}

public static void main(String args[]) {
public static void main(String args[]) {
test("file", "output.txt");
test("file", "output.txt");
test("file", File.seperator + "output.txt");
test("file", File.seperator + "output.txt");

test("directory", "docs");
test("directory", "docs");
test("directory", File.seperator + "docs" + File.seperator);
test("directory", File.seperator + "docs" + File.seperator);

Revision as of 14:44, 7 April 2007

Task
Create a file
You are encouraged to solve this task according to the task description, using any language you may know.

In this task, the job is to create a new empty file called "output.txt" with no content and of size 0 byte and an empty directory called "docs". Assuming current directory or fullpath. Either "/output.txt" or "\output.txt" for the former and "/docs/" or "\docs\" for the second test.

Java

public class CreateFileTest {
   public static String createNewFile(String filename) {
       try {
           // Create file if it does not exist
           boolean success = new File(filename).createNewFile();
           if (success) {
               return " did not exist and was created successfully.";
           } else {
               return " already exists.";
           }
       } catch (IOException e) {
               return " could not be created.";
       }
   }
   public static void test(String type, String filename) {
       System.out.println("The following " + type + " called " + filename + 
           createNewFile(filename)
       );
   }
   public static void main(String args[]) {
        test("file", "output.txt");
        test("file", File.seperator + "output.txt");
        test("directory", "docs");
        test("directory", File.seperator + "docs" + File.seperator);
   }
}

Bash

 touch output.txt
 touch /output.txt
 mkdir docs
 mkdir /docs

DOS

 md docs
 md \docs