Check that file exists: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
Line 12: Line 12:
return exists;
return exists;
}
}

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 18: Line 17:
);
);
}
}

public static void main(String args[]) {
public static void main(String args[]) {
test("file", "input.txt");
test("file", "input.txt");
test("file", File.seperator + "input.txt");
test("file", File.seperator + "input.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
Check that file exists
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 verify that a file called "input.txt" exists or not and that the directory "docs" exists or not. Assuming current directory or fullpath. Either "/input.txt" or "\input.txt" for the former and "/docs/" or "\docs\" for the second test.


Java

public class FileTest {
   public static boolean isFileExist(String filename) {
       boolean exists = new File(filename).exists();
       return exists;
   }
   public static void test(String type, String filename) {
       System.out.println("The following " + type + " called " + filename + 
           (isFileExist(filename) ? " exists." : " not exists.")
       );
   }
   public static void main(String args[]) {
        test("file", "input.txt");
        test("file", File.seperator + "input.txt");
        test("directory", "docs");
        test("directory", File.seperator + "docs" + File.seperator);
   }
}