Home | History | Annotate | Download | only in io
      1 /*
      2  *  Licensed to the Apache Software Foundation (ASF) under one or more
      3  *  contributor license agreements.  See the NOTICE file distributed with
      4  *  this work for additional information regarding copyright ownership.
      5  *  The ASF licenses this file to You under the Apache License, Version 2.0
      6  *  (the "License"); you may not use this file except in compliance with
      7  *  the License.  You may obtain a copy of the License at
      8  *
      9  *     http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  *  Unless required by applicable law or agreed to in writing, software
     12  *  distributed under the License is distributed on an "AS IS" BASIS,
     13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  *  See the License for the specific language governing permissions and
     15  *  limitations under the License.
     16  */
     17 
     18 package org.apache.harmony.tests.java.io;
     19 
     20 import java.io.File;
     21 import java.io.FileFilter;
     22 import java.io.FileOutputStream;
     23 import java.io.FilenameFilter;
     24 import java.io.IOException;
     25 import java.io.ObjectStreamClass;
     26 import java.io.ObjectStreamField;
     27 import java.io.RandomAccessFile;
     28 import java.net.MalformedURLException;
     29 import java.net.URI;
     30 import java.net.URISyntaxException;
     31 import java.net.URL;
     32 import junit.framework.TestCase;
     33 import libcore.io.Libcore;
     34 import org.apache.harmony.testframework.serialization.SerializationTest;
     35 
     36 public class FileTest extends TestCase {
     37 
     38     private static String platformId = "JDK"
     39             + System.getProperty("java.vm.version").replace('.', '-');
     40 
     41     private static void deleteTempFolder(File dir) {
     42         String files[] = dir.list();
     43         if (files != null) {
     44             for (int i = 0; i < files.length; i++) {
     45                 File f = new File(dir, files[i]);
     46                 if (f.isDirectory()) {
     47                     deleteTempFolder(f);
     48                 } else {
     49                     f.delete();
     50                 }
     51             }
     52         }
     53         dir.delete();
     54     }
     55 
     56     private static String addTrailingSlash(String path) {
     57         if (File.separatorChar == path.charAt(path.length() - 1)) {
     58             return path;
     59         }
     60         return path + File.separator;
     61     }
     62 
     63     /**
     64      * Location to store tests in
     65      */
     66     private File tempDirectory;
     67 
     68     public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_File\nTest_FileDescriptor\nTest_FileInputStream\nTest_FileNotFoundException\nTest_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
     69 
     70     protected void setUp() throws IOException {
     71         /** Setup the temporary directory */
     72         tempDirectory = new File(addTrailingSlash(System.getProperty("java.io.tmpdir")) + "harmony-test-" + getClass().getSimpleName() + File.separator);
     73         tempDirectory.mkdirs();
     74     }
     75 
     76     protected void tearDown() {
     77         if (tempDirectory != null) {
     78             deleteTempFolder(tempDirectory);
     79             tempDirectory = null;
     80         }
     81     }
     82 
     83     /**
     84      * java.io.File#File(java.io.File, java.lang.String)
     85      */
     86     public void test_ConstructorLjava_io_FileLjava_lang_String0() {
     87         File f = new File(tempDirectory.getPath(), "input.tst");
     88         assertEquals("Created Incorrect File ", addTrailingSlash(tempDirectory.getPath()) + "input.tst", f.getPath());
     89     }
     90 
     91     public void test_ConstructorLjava_io_FileLjava_lang_String1() {
     92         try {
     93             new File(tempDirectory, null);
     94             fail("NullPointerException Not Thrown.");
     95         } catch (NullPointerException e) {
     96         }
     97     }
     98 
     99     public void test_ConstructorLjava_io_FileLjava_lang_String2() throws IOException {
    100         File f = new File((File) null, "input.tst");
    101         assertEquals("Created Incorrect File",
    102                 new File("input.tst").getAbsolutePath(),
    103                 f.getAbsolutePath());
    104     }
    105 
    106     public void test_ConstructorLjava_io_FileLjava_lang_String3() {
    107         // Regression test for HARMONY-382
    108         File f = new File("/abc");
    109         File d = new File((File) null, "/abc");
    110         assertEquals("Test3: Created Incorrect File",
    111                 d.getAbsolutePath(), f.getAbsolutePath());
    112     }
    113 
    114     public void test_ConstructorLjava_io_FileLjava_lang_String4() {
    115         // Regression test for HARMONY-21
    116         File path = new File("/dir/file");
    117         File root = new File("/");
    118         File file = new File(root, "/dir/file");
    119         assertEquals("Assert 1: wrong path result ", path.getPath(), file
    120                 .getPath());
    121         if (File.separatorChar == '\\') {
    122             assertTrue("Assert 1.1: path not absolute ", new File("\\\\\\a\b")
    123                     .isAbsolute());
    124         } else {
    125             assertFalse("Assert 1.1: path absolute ", new File("\\\\\\a\b")
    126                     .isAbsolute());
    127         }
    128     }
    129 
    130     public void test_ConstructorLjava_io_FileLjava_lang_String5() {
    131         // Test data used in a few places below
    132         String dirName = tempDirectory.getPath();
    133         String fileName = "input.tst";
    134 
    135         // Check filename is preserved correctly
    136         File d = new File(dirName);
    137         File f = new File(d, fileName);
    138         dirName = addTrailingSlash(dirName);
    139         dirName += fileName;
    140         assertEquals("Assert 1: Created incorrect file ",
    141                 dirName, f.getPath());
    142 
    143         // Check null argument is handled
    144         try {
    145             f = new File(d, null);
    146             fail("Assert 2: NullPointerException not thrown.");
    147         } catch (NullPointerException e) {
    148             // Expected.
    149         }
    150     }
    151 
    152     public void test_ConstructorLjava_io_FileLjava_lang_String6() {
    153         // Regression for HARMONY-46
    154         File f1 = new File("a");
    155         File f2 = new File("a/");
    156         assertEquals("Trailing slash file name is incorrect", f1, f2);
    157     }
    158 
    159     /**
    160      * java.io.File#File(java.lang.String)
    161      */
    162     public void test_ConstructorLjava_lang_String() {
    163         String fileName = null;
    164         try {
    165             new File(fileName);
    166             fail("NullPointerException Not Thrown.");
    167         } catch (NullPointerException e) {
    168             // Expected
    169         }
    170 
    171         fileName = addTrailingSlash(tempDirectory.getPath());
    172         fileName += "input.tst";
    173 
    174         File f = new File(fileName);
    175         assertEquals("Created incorrect File", fileName, f.getPath());
    176     }
    177 
    178     /**
    179      * java.io.File#File(java.lang.String, java.lang.String)
    180      */
    181     public void test_ConstructorLjava_lang_StringLjava_lang_String() throws IOException {
    182         String dirName = null;
    183         String fileName = "input.tst";
    184         File f = new File(dirName, fileName);
    185         assertEquals("Test 1: Created Incorrect File",
    186                 new File("input.tst").getAbsolutePath(),
    187                 f.getAbsolutePath());
    188 
    189         dirName = tempDirectory.getPath();
    190         fileName = null;
    191         try {
    192             f = new File(dirName, fileName);
    193             fail("NullPointerException Not Thrown.");
    194         } catch (NullPointerException e) {
    195             // Expected
    196         }
    197 
    198         fileName = "input.tst";
    199         f = new File(dirName, fileName);
    200         assertEquals("Test 2: Created Incorrect File",
    201                 addTrailingSlash(tempDirectory.getPath()) + "input.tst",
    202                 f.getPath());
    203 
    204         // Regression test for HARMONY-382
    205         String s = null;
    206         f = new File("/abc");
    207         File d = new File(s, "/abc");
    208         assertEquals("Test3: Created Incorrect File", d.getAbsolutePath(), f
    209                 .getAbsolutePath());
    210     }
    211 
    212     /**
    213      * java.io.File#File(java.lang.String, java.lang.String)
    214      */
    215     public void test_Constructor_String_String_112270() {
    216         File ref1 = new File("/dir1/file1");
    217 
    218         File file1 = new File("/", "/dir1/file1");
    219         assertEquals("wrong result 1", ref1.getPath(), file1.getPath());
    220         File file2 = new File("/", "//dir1/file1");
    221         assertEquals("wrong result 2", ref1.getPath(), file2.getPath());
    222 
    223         if (File.separatorChar == '\\') {
    224             File file3 = new File("\\", "\\dir1\\file1");
    225             assertEquals("wrong result 3", ref1.getPath(), file3.getPath());
    226             File file4 = new File("\\", "\\\\dir1\\file1");
    227             assertEquals("wrong result 4", ref1.getPath(), file4.getPath());
    228         }
    229 
    230         File ref2 = new File("/lib/test_112270.properties");
    231         File file5 = new File("/", "lib/test_112270.properties");
    232         assertEquals("wrong result 5", ref2.getPath(), file5.getPath());
    233     }
    234 
    235     /**
    236      * java.io.File#File(java.io.File, java.lang.String)
    237      */
    238     public void test_Constructor_File_String_112270() {
    239         File ref1 = new File("/dir1/file1");
    240 
    241         File root = new File("/");
    242         File file1 = new File(root, "/dir1/file1");
    243         assertEquals("wrong result 1", ref1.getPath(), file1.getPath());
    244         File file2 = new File(root, "//dir1/file1");
    245         assertEquals("wrong result 2", ref1.getPath(), file2.getPath());
    246 
    247         if (File.separatorChar == '\\') {
    248             File file3 = new File(root, "\\dir1\\file1");
    249             assertEquals("wrong result 3", ref1.getPath(), file3.getPath());
    250             File file4 = new File(root, "\\\\dir1\\file1");
    251             assertEquals("wrong result 4", ref1.getPath(), file4.getPath());
    252         }
    253 
    254         File ref2 = new File("/lib/content-types.properties");
    255         File file5 = new File(root, "lib/content-types.properties");
    256         assertEquals("wrong result 5", ref2.getPath(), file5.getPath());
    257     }
    258 
    259     /**
    260      * java.io.File#File(java.net.URI)
    261      */
    262     public void test_ConstructorLjava_net_URI() throws URISyntaxException {
    263         URI uri = null;
    264         try {
    265             new File(uri);
    266             fail("NullPointerException Not Thrown.");
    267         } catch (NullPointerException e) {
    268             // Expected
    269         }
    270 
    271         // invalid file URIs
    272         String[] uris = new String[] { "mailto:user (at) domain.com", // not
    273                 // hierarchical
    274                 "ftp:///path", // not file scheme
    275                 "//host/path/", // not absolute
    276                 "file://host/path", // non empty authority
    277                 "file:///path?query", // non empty query
    278                 "file:///path#fragment", // non empty fragment
    279                 "file:///path?", "file:///path#" };
    280 
    281         for (int i = 0; i < uris.length; i++) {
    282             uri = new URI(uris[i]);
    283             try {
    284                 new File(uri);
    285                 fail("Expected IllegalArgumentException for new File(" + uri
    286                         + ")");
    287             } catch (IllegalArgumentException e) {
    288                 // Expected
    289             }
    290         }
    291 
    292         // a valid File URI
    293         File f = new File(new URI("file:///pa%20th/another\u20ac/pa%25th"));
    294         assertTrue("Created incorrect File " + f.getPath(), f.getPath().equals(
    295                 File.separator + "pa th" + File.separator + "another\u20ac" + File.separator + "pa%th"));
    296     }
    297 
    298     /**
    299      * java.io.File#canRead()
    300      */
    301     public void test_canRead() throws IOException {
    302         // canRead only returns if the file exists so cannot be fully tested.
    303         File f = new File(tempDirectory, platformId + "canRead.tst");
    304         try {
    305             FileOutputStream fos = new FileOutputStream(f);
    306             fos.close();
    307             assertTrue("canRead returned false", f.canRead());
    308         } finally {
    309             f.delete();
    310         }
    311     }
    312 
    313     /**
    314      * java.io.File#canWrite()
    315      */
    316     public void test_canWrite() throws IOException {
    317         // canWrite only returns if the file exists so cannot be fully tested.
    318         File f = new File(tempDirectory, platformId + "canWrite.tst");
    319         try {
    320             FileOutputStream fos = new FileOutputStream(f);
    321             fos.close();
    322             assertTrue("canWrite returned false", f.canWrite());
    323         } finally {
    324             f.delete();
    325         }
    326     }
    327 
    328     /**
    329      * java.io.File#compareTo(java.io.File)
    330      */
    331     public void test_compareToLjava_io_File() {
    332         File f1 = new File("thisFile.file");
    333         File f2 = new File("thisFile.file");
    334         File f3 = new File("thatFile.file");
    335         assertEquals("Equal files did not answer zero for compareTo", 0, f1
    336                 .compareTo(f2));
    337         assertTrue("f3.compareTo(f1) did not result in value < 0", f3
    338                 .compareTo(f1) < 0);
    339         assertTrue("f1.compareTo(f3) did not result in value > 0", f1
    340                 .compareTo(f3) > 0);
    341     }
    342 
    343     /**
    344      * java.io.File#createNewFile()
    345      */
    346     public void test_createNewFile_EmptyString() {
    347         File f = new File("");
    348         try {
    349             f.createNewFile();
    350             fail("should throw IOException");
    351         } catch (IOException e) {
    352             // expected
    353         }
    354     }
    355 
    356     /**
    357      * java.io.File#createNewFile()
    358      */
    359     public void test_createNewFile() throws IOException {
    360         String base = tempDirectory.getPath();
    361         boolean dirExists = true;
    362         int numDir = 1;
    363         File dir = new File(base, String.valueOf(numDir));
    364         // Making sure that the directory does not exist.
    365         while (dirExists) {
    366             // If the directory exists, add one to the directory number
    367             // (making it a new directory name.)
    368             if (dir.exists()) {
    369                 numDir++;
    370                 dir = new File(base, String.valueOf(numDir));
    371             } else {
    372                 dirExists = false;
    373             }
    374         }
    375 
    376         // Test for trying to create a file in a directory that does not
    377         // exist.
    378         try {
    379             // Try to create a file in a directory that does not exist
    380             File f1 = new File(dir, "tempfile.tst");
    381             f1.createNewFile();
    382             fail("IOException not thrown");
    383         } catch (IOException e) {
    384             // Expected
    385         }
    386 
    387         dir.mkdir();
    388 
    389         File f1 = new File(dir, "tempfile.tst");
    390         File f2 = new File(dir, "tempfile.tst");
    391         f1.deleteOnExit();
    392         f2.deleteOnExit();
    393         dir.deleteOnExit();
    394         assertFalse("File Should Not Exist", f1.isFile());
    395         f1.createNewFile();
    396         assertTrue("File Should Exist.", f1.isFile());
    397         assertTrue("File Should Exist.", f2.isFile());
    398         String dirName = f1.getParent();
    399         if (!dirName.endsWith(File.separator)) {
    400             dirName += File.separator;
    401         }
    402         assertEquals("File Saved To Wrong Directory.",
    403                 dir.getPath() + File.separator, dirName);
    404         assertEquals("File Saved With Incorrect Name.", "tempfile.tst",
    405                 f1.getName());
    406 
    407         // Test for creating a file that already exists.
    408         assertFalse("File Already Exists, createNewFile Should Return False.",
    409                 f2.createNewFile());
    410 
    411         // Test create an illegal file
    412         String sep = File.separator;
    413         f1 = new File(sep + "..");
    414         try {
    415             f1.createNewFile();
    416             fail("should throw IOE");
    417         } catch (IOException e) {
    418             // expected;
    419         }
    420         f1 = new File(sep + "a" + sep + ".." + sep + ".." + sep);
    421         try {
    422             f1.createNewFile();
    423             fail("should throw IOE");
    424         } catch (IOException e) {
    425             // expected;
    426         }
    427 
    428         // This test is invalid. createNewFile should return false
    429         // not IOE when the file exists (in this case it exists and is
    430         // a directory). TODO: We should probably replace this test
    431         // with some that cover this behaviour. It might even be
    432         // different on unix and windows since it directly reflects
    433         // the open syscall behaviour.
    434         //
    435         // // Test create an exist path
    436         // f1 = new File(base);
    437         // try {
    438         // assertFalse(f1.createNewFile());
    439         // fail("should throw IOE");
    440         // } catch (IOException e) {
    441         // // expected;
    442         // }
    443     }
    444 
    445     /**
    446      * java.io.File#createTempFile(java.lang.String, java.lang.String)
    447      */
    448     public void test_createTempFileLjava_lang_StringLjava_lang_String()
    449             throws IOException {
    450         // Error protection against using a suffix without a "."?
    451         File f1 = null;
    452         File f2 = null;
    453         try {
    454             f1 = File.createTempFile("harmony-test-FileTest_tempFile_abc", ".tmp");
    455             f2 = File.createTempFile("harmony-test-FileTest_tempFile_tf", null);
    456 
    457             String fileLocation = addTrailingSlash(f1.getParent());
    458 
    459             String tempDir = addTrailingSlash(System.getProperty("java.io.tmpdir"));
    460 
    461             assertEquals(
    462                     "File did not save to the default temporary-file location.",
    463                     tempDir, fileLocation);
    464 
    465             // Test to see if correct suffix was used to create the tempfile.
    466             File currentFile;
    467             String fileName;
    468             // Testing two files, one with suffix ".tmp" and one with null
    469             for (int i = 0; i < 2; i++) {
    470                 currentFile = i == 0 ? f1 : f2;
    471                 fileName = currentFile.getPath();
    472                 assertTrue("File Created With Incorrect Suffix.", fileName
    473                         .endsWith(".tmp"));
    474             }
    475 
    476             // Tests to see if the correct prefix was used to create the
    477             // tempfiles.
    478             fileName = f1.getName();
    479             assertTrue("Test 1: File Created With Incorrect Prefix.", fileName
    480                     .startsWith("harmony-test-FileTest_tempFile_abc"));
    481             fileName = f2.getName();
    482             assertTrue("Test 2: File Created With Incorrect Prefix.", fileName
    483                     .startsWith("harmony-test-FileTest_tempFile_tf"));
    484 
    485             // Tests for creating a tempfile with a filename shorter than 3
    486             // characters.
    487             try {
    488                 File f3 = File.createTempFile("ab", ".tst");
    489                 f3.delete();
    490                 fail("IllegalArgumentException Not Thrown.");
    491             } catch (IllegalArgumentException e) {
    492                 // Expected
    493             }
    494             try {
    495                 File f3 = File.createTempFile("a", ".tst");
    496                 f3.delete();
    497                 fail("IllegalArgumentException Not Thrown.");
    498             } catch (IllegalArgumentException e) {
    499                 // Expected
    500             }
    501             try {
    502                 File f3 = File.createTempFile("", ".tst");
    503                 f3.delete();
    504                 fail("IllegalArgumentException Not Thrown.");
    505             } catch (IllegalArgumentException e) {
    506                 // Expected
    507             }
    508         } finally {
    509             if (f1 != null) {
    510                 f1.delete();
    511             }
    512             if (f2 != null) {
    513                 f2.delete();
    514             }
    515         }
    516     }
    517 
    518     /**
    519      * java.io.File#createTempFile(java.lang.String, java.lang.String,
    520      *java.io.File)
    521      */
    522     public void test_createTempFileLjava_lang_StringLjava_lang_StringLjava_io_File()
    523             throws IOException {
    524         File f1 = null;
    525         File f2 = null;
    526         String base = System.getProperty("java.io.tmpdir");
    527         try {
    528             // Test to make sure that the tempfile was saved in the correct
    529             // location and with the correct prefix/suffix.
    530             f1 = File.createTempFile("harmony-test-FileTest_tempFile2_tf", null, null);
    531             File dir = new File(base);
    532             f2 = File.createTempFile("harmony-test-FileTest_tempFile2_tf", ".tmp", dir);
    533             File currentFile;
    534             String fileLocation;
    535             String fileName;
    536             for (int i = 0; i < 2; i++) {
    537                 currentFile = i == 0 ? f1 : f2;
    538                 fileLocation = addTrailingSlash(currentFile.getParent());
    539                 base = addTrailingSlash(base);
    540                 assertEquals(
    541                         "File not created in the default temporary-file location.",
    542                         base, fileLocation);
    543                 fileName = currentFile.getName();
    544                 assertTrue("File created with incorrect suffix.", fileName
    545                         .endsWith(".tmp"));
    546                 assertTrue("File created with incorrect prefix.", fileName
    547                         .startsWith("harmony-test-FileTest_tempFile2_tf"));
    548                 currentFile.delete();
    549             }
    550 
    551             // Test for creating a tempfile in a directory that does not exist.
    552             int dirNumber = 1;
    553             boolean dirExists = true;
    554             // Set dir to a non-existent directory inside the temporary
    555             // directory
    556             dir = new File(base, String.valueOf(dirNumber));
    557             // Making sure that the directory does not exist.
    558             while (dirExists) {
    559                 // If the directory exists, add one to the directory number
    560                 // (making it
    561                 // a new directory name.)
    562                 if (dir.exists()) {
    563                     dirNumber++;
    564                     dir = new File(base, String.valueOf(dirNumber));
    565                 } else {
    566                     dirExists = false;
    567                 }
    568             }
    569             try {
    570                 // Try to create a file in a directory that does not exist
    571                 File f3 = File.createTempFile("harmony-test-FileTest_tempFile2_tf", null, dir);
    572                 f3.delete();
    573                 fail("IOException not thrown");
    574             } catch (IOException e) {
    575                 // Expected
    576             }
    577             dir.delete();
    578 
    579             // Tests for creating a tempfile with a filename shorter than 3
    580             // characters.
    581             try {
    582                 File f4 = File.createTempFile("ab", null, null);
    583                 f4.delete();
    584                 fail("IllegalArgumentException not thrown.");
    585             } catch (IllegalArgumentException e) {
    586                 // Expected
    587             }
    588             try {
    589                 File f4 = File.createTempFile("a", null, null);
    590                 f4.delete();
    591                 fail("IllegalArgumentException not thrown.");
    592             } catch (IllegalArgumentException e) {
    593                 // Expected
    594             }
    595             try {
    596                 File f4 = File.createTempFile("", null, null);
    597                 f4.delete();
    598                 fail("IllegalArgumentException not thrown.");
    599             } catch (IllegalArgumentException e) {
    600                 // Expected
    601             }
    602         } finally {
    603             if (f1 != null) {
    604                 f1.delete();
    605             }
    606             if (f2 != null) {
    607                 f1.delete();
    608             }
    609         }
    610     }
    611 
    612     /**
    613      * java.io.File#delete()
    614      */
    615     public void test_delete() throws IOException {
    616         File dir = new File(tempDirectory, platformId
    617                 + "filechk");
    618         dir.mkdir();
    619         assertTrue("Directory does not exist", dir.exists());
    620         assertTrue("Directory is not directory", dir.isDirectory());
    621         File f = new File(dir, "filechk.tst");
    622         FileOutputStream fos = new FileOutputStream(f);
    623         fos.close();
    624         assertTrue("Error Creating File For Delete Test", f.exists());
    625         dir.delete();
    626         assertTrue("Directory Should Not Have Been Deleted.", dir.exists());
    627         f.delete();
    628         assertTrue("File Was Not Deleted", !f.exists());
    629         dir.delete();
    630         assertTrue("Directory Was Not Deleted", !dir.exists());
    631     }
    632 
    633     // GCH
    634     // TODO : This test passes on Windows but fails on Linux with a
    635     // java.lang.NoClassDefFoundError. Temporarily removing from the test
    636     // suite while I investigate the cause.
    637     // /**
    638     // * java.io.File#deleteOnExit()
    639     // */
    640     // public void test_deleteOnExit() {
    641     // File f1 = new File(System.getProperty("java.io.tmpdir"), platformId
    642     // + "deleteOnExit.tst");
    643     // try {
    644     // FileOutputStream fos = new FileOutputStream(f1);
    645     // fos.close();
    646     // } catch (IOException e) {
    647     // fail("Unexpected IOException During Test : " + e.getMessage());
    648     // }
    649     // assertTrue("File Should Exist.", f1.exists());
    650     //
    651     // try {
    652     // Support_Exec.execJava(new String[] {
    653     // "tests.support.Support_DeleteOnExitTest", f1.getPath() },
    654     // null, true);
    655     // } catch (IOException e) {
    656     // fail("Unexpected IOException During Test + " + e.getMessage());
    657     // } catch (InterruptedException e) {
    658     // fail("Unexpected InterruptedException During Test: " + e);
    659     // }
    660     //
    661     // boolean gone = !f1.exists();
    662     // f1.delete();
    663     // assertTrue("File Should Already Be Deleted.", gone);
    664     // }
    665 
    666     /**
    667      * java.io.File#equals(java.lang.Object)
    668      */
    669     public void test_equalsLjava_lang_Object() throws IOException {
    670         File f1 = new File("filechk.tst");
    671         File f2 = new File("filechk.tst");
    672         File f3 = new File("xxxx");
    673 
    674         assertTrue("Equality test failed", f1.equals(f2));
    675         assertTrue("Files Should Not Return Equal.", !f1.equals(f3));
    676 
    677         f1 = new File(tempDirectory, "casetest.tmp");
    678         f2 = new File(tempDirectory, "CaseTest.tmp");
    679         assertFalse(f1.equals(f2));
    680         assertTrue(f1.createNewFile());
    681         f1.delete();
    682     }
    683 
    684     /**
    685      * java.io.File#exists()
    686      */
    687     public void test_exists() throws IOException {
    688         File f = new File(tempDirectory, platformId
    689                 + "exists.tst");
    690         assertTrue("Exists returned true for non-existent file", !f.exists());
    691         FileOutputStream fos = new FileOutputStream(f);
    692         fos.close();
    693         assertTrue("Exists returned false file", f.exists());
    694         f.delete();
    695     }
    696 
    697     /**
    698      * java.io.File#getAbsoluteFile()
    699      */
    700     public void test_getAbsoluteFile() {
    701         String base = addTrailingSlash(tempDirectory.getPath());
    702         File f = new File(base, "temp.tst");
    703         File f2 = f.getAbsoluteFile();
    704         assertEquals("Test 1: Incorrect File Returned.", 0, f2.compareTo(f
    705                 .getAbsoluteFile()));
    706         f = new File(base + "Temp" + File.separator + File.separator + "temp.tst");
    707         f2 = f.getAbsoluteFile();
    708         assertEquals("Test 2: Incorrect File Returned.", 0, f2.compareTo(f
    709                 .getAbsoluteFile()));
    710         f = new File(base + File.separator + ".." + File.separator + "temp.tst");
    711         f2 = f.getAbsoluteFile();
    712         assertEquals("Test 3: Incorrect File Returned.", 0, f2.compareTo(f
    713                 .getAbsoluteFile()));
    714         f.delete();
    715         f2.delete();
    716     }
    717 
    718     /**
    719      * java.io.File#getAbsolutePath()
    720      */
    721     public void test_getAbsolutePath() {
    722         String base = addTrailingSlash(tempDirectory.getPath());
    723         File f = new File(base, "temp.tst");
    724         assertEquals("Test 1: Incorrect Path Returned.",
    725                 base + "temp.tst", f.getAbsolutePath());
    726 
    727         f = new File(base + "Temp" + File.separator + File.separator + File.separator + "Testing" + File.separator
    728                 + "temp.tst");
    729         assertEquals("Test 2: Incorrect Path Returned.",
    730                 base + "Temp" + File.separator + "Testing" + File.separator + "temp.tst",
    731                 f.getAbsolutePath());
    732 
    733         f = new File(base + "a" + File.separator + File.separator + ".." + File.separator + "temp.tst");
    734         assertEquals("Test 3: Incorrect Path Returned.",
    735                 base + "a" + File.separator + ".." + File.separator + "temp.tst",
    736                 f.getAbsolutePath());
    737         f.delete();
    738     }
    739 
    740     /**
    741      * java.io.File#getCanonicalFile()
    742      */
    743     public void test_getCanonicalFile() throws IOException {
    744         String base = addTrailingSlash(tempDirectory.getPath());
    745         File f = new File(base, "temp.tst");
    746         File f2 = f.getCanonicalFile();
    747         assertEquals("Test 1: Incorrect File Returned.", 0, f2
    748                 .getCanonicalFile().compareTo(f.getCanonicalFile()));
    749         f = new File(base + "Temp" + File.separator + File.separator + "temp.tst");
    750         f2 = f.getCanonicalFile();
    751         assertEquals("Test 2: Incorrect File Returned.", 0, f2
    752                 .getCanonicalFile().compareTo(f.getCanonicalFile()));
    753         f = new File(base + "Temp" + File.separator + File.separator + ".." + File.separator + "temp.tst");
    754         f2 = f.getCanonicalFile();
    755         assertEquals("Test 3: Incorrect File Returned.", 0, f2
    756                 .getCanonicalFile().compareTo(f.getCanonicalFile()));
    757 
    758         // Test for when long directory/file names in Windows
    759         boolean onWindows = File.separatorChar == '\\';
    760         if (onWindows) {
    761             File testdir = new File(base, "long-" + platformId);
    762             testdir.mkdir();
    763             File dir = new File(testdir, "longdirectory" + platformId);
    764             try {
    765                 dir.mkdir();
    766                 f = new File(dir, "longfilename.tst");
    767                 f2 = f.getCanonicalFile();
    768                 assertEquals("Test 4: Incorrect File Returned.", 0, f2
    769                         .getCanonicalFile().compareTo(f.getCanonicalFile()));
    770                 FileOutputStream fos = new FileOutputStream(f);
    771                 fos.close();
    772                 f2 = new File(testdir + File.separator + "longdi~1" + File.separator
    773                         + "longfi~1.tst");
    774                 File canonicalf2 = f2.getCanonicalFile();
    775                 /*
    776                  * If the "short file name" doesn't exist, then assume that the
    777                  * 8.3 file name compatibility is disabled.
    778                  */
    779                 if (canonicalf2.exists()) {
    780                     assertTrue("Test 5: Incorrect File Returned: "
    781                             + canonicalf2, canonicalf2.compareTo(f
    782                             .getCanonicalFile()) == 0);
    783                 }
    784             } finally {
    785                 f.delete();
    786                 f2.delete();
    787                 dir.delete();
    788                 testdir.delete();
    789             }
    790         }
    791     }
    792 
    793     /**
    794      * java.io.File#getCanonicalPath()
    795      */
    796     public void test_getCanonicalPath() throws IOException {
    797         // Should work for Unix/Windows.
    798         String dots = "..";
    799         String base = tempDirectory.getCanonicalPath();
    800         base = addTrailingSlash(base);
    801         File f = new File(base, "temp.tst");
    802         assertEquals("Test 1: Incorrect Path Returned.", base + "temp.tst", f
    803                 .getCanonicalPath());
    804         f = new File(base + "Temp" + File.separator + dots + File.separator + "temp.tst");
    805         assertEquals("Test 2: Incorrect Path Returned.", base + "temp.tst", f
    806                 .getCanonicalPath());
    807 
    808         // Finding a non-existent directory for tests 3 and 4
    809         // This is necessary because getCanonicalPath is case sensitive and
    810         // could cause a failure in the test if the directory exists but with
    811         // different case letters (e.g "Temp" and "temp")
    812         int dirNumber = 1;
    813         boolean dirExists = true;
    814         File dir1 = new File(base, String.valueOf(dirNumber));
    815         while (dirExists) {
    816             if (dir1.exists()) {
    817                 dirNumber++;
    818                 dir1 = new File(base, String.valueOf(dirNumber));
    819             } else {
    820                 dirExists = false;
    821             }
    822         }
    823         f = new File(base + dirNumber + File.separator + dots + File.separator + dirNumber
    824                 + File.separator + "temp.tst");
    825         assertEquals("Test 3: Incorrect Path Returned.", base + dirNumber
    826                 + File.separator + "temp.tst", f.getCanonicalPath());
    827         f = new File(base + dirNumber + File.separator + "Temp" + File.separator + dots + File.separator
    828                 + "Test" + File.separator + "temp.tst");
    829         assertEquals("Test 4: Incorrect Path Returned.", base + dirNumber
    830                 + File.separator + "Test" + File.separator + "temp.tst", f.getCanonicalPath());
    831 
    832         f = new File(base + "1234.567");
    833         assertEquals("Test 5: Incorrect Path Returned.", base + "1234.567", f
    834                 .getCanonicalPath());
    835 
    836         // Test for long file names on Windows
    837         boolean onWindows = (File.separatorChar == '\\');
    838         if (onWindows) {
    839             File testdir = new File(base, "long-" + platformId);
    840             testdir.mkdir();
    841             File f1 = new File(testdir, "longfilename" + platformId + ".tst");
    842             FileOutputStream fos = new FileOutputStream(f1);
    843             File f2 = null, f3 = null, dir2 = null;
    844             try {
    845                 fos.close();
    846                 String dirName1 = f1.getCanonicalPath();
    847                 File f4 = new File(testdir, "longfi~1.tst");
    848                 /*
    849                  * If the "short file name" doesn't exist, then assume that the
    850                  * 8.3 file name compatibility is disabled.
    851                  */
    852                 if (f4.exists()) {
    853                     String dirName2 = f4.getCanonicalPath();
    854                     assertEquals("Test 6: Incorrect Path Returned.", dirName1,
    855                             dirName2);
    856                     dir2 = new File(testdir, "longdirectory" + platformId);
    857                     if (!dir2.exists()) {
    858                         assertTrue("Could not create dir: " + dir2, dir2
    859                                 .mkdir());
    860                     }
    861                     f2 = new File(testdir.getPath() + File.separator + "longdirectory"
    862                             + platformId + File.separator + "Test" + File.separator + dots
    863                             + File.separator + "longfilename.tst");
    864                     FileOutputStream fos2 = new FileOutputStream(f2);
    865                     fos2.close();
    866                     dirName1 = f2.getCanonicalPath();
    867                     f3 = new File(testdir.getPath() + File.separator + "longdi~1"
    868                             + File.separator + "Test" + File.separator + dots + File.separator
    869                             + "longfi~1.tst");
    870                     dirName2 = f3.getCanonicalPath();
    871                     assertEquals("Test 7: Incorrect Path Returned.", dirName1,
    872                             dirName2);
    873                 }
    874             } finally {
    875                 f1.delete();
    876                 if (f2 != null) {
    877                     f2.delete();
    878                 }
    879                 if (dir2 != null) {
    880                     dir2.delete();
    881                 }
    882                 testdir.delete();
    883             }
    884         }
    885     }
    886 
    887     /**
    888      * java.io.File#getName()
    889      */
    890     public void test_getName() {
    891         File f = new File("name.tst");
    892         assertEquals("Test 1: Returned incorrect name", "name.tst", f.getName());
    893 
    894         f = new File("");
    895         assertEquals("Test 2: Returned incorrect name", "", f.getName());
    896 
    897         f.delete();
    898     }
    899 
    900     /**
    901      * java.io.File#getParent()
    902      */
    903     public void test_getParent() {
    904         File f = new File("p.tst");
    905         assertNull("Incorrect path returned", f.getParent());
    906         f = new File("/user/home/p.tst");
    907         assertEquals("Incorrect path returned",
    908                 "/user/home", f.getParent());
    909 
    910         File f1 = new File("/directory");
    911         assertEquals("Wrong parent test 1", File.separator, f1.getParent());
    912         f1 = new File("/directory/file");
    913         assertEquals("Wrong parent test 2",
    914                 File.separator + "directory", f1.getParent());
    915         f1 = new File("directory/file");
    916         assertEquals("Wrong parent test 3", "directory", f1.getParent());
    917         f1 = new File("/");
    918         assertNull("Wrong parent test 4", f1.getParent());
    919         f1 = new File("directory");
    920         assertNull("Wrong parent test 5", f1.getParent());
    921 
    922         if (File.separatorChar == '\\' && new File("d:/").isAbsolute()) {
    923             f1 = new File("d:/directory");
    924             assertEquals("Wrong parent test 1a", "d:" + File.separator, f1.getParent());
    925             f1 = new File("d:/directory/file");
    926             assertEquals("Wrong parent test 2a",
    927                     "d:" + File.separator + "directory", f1.getParent());
    928             f1 = new File("d:directory/file");
    929             assertEquals("Wrong parent test 3a", "d:directory", f1.getParent());
    930             f1 = new File("d:/");
    931             assertNull("Wrong parent test 4a", f1.getParent());
    932             f1 = new File("d:directory");
    933             assertEquals("Wrong parent test 5a", "d:", f1.getParent());
    934         }
    935     }
    936 
    937     /**
    938      * java.io.File#getParentFile()
    939      */
    940     public void test_getParentFile() {
    941         File f = new File("tempfile.tst");
    942         assertNull("Incorrect path returned", f.getParentFile());
    943         f = new File(tempDirectory, "tempfile1.tmp");
    944         File f2 = new File(tempDirectory, "tempfile2.tmp");
    945         File f3 = new File(tempDirectory, "/a/tempfile.tmp");
    946         assertEquals("Incorrect File Returned", 0, f.getParentFile().compareTo(
    947                 f2.getParentFile()));
    948         assertTrue("Incorrect File Returned", f.getParentFile().compareTo(
    949                 f3.getParentFile()) != 0);
    950         f.delete();
    951         f2.delete();
    952         f3.delete();
    953     }
    954 
    955     /**
    956      * java.io.File#getPath()
    957      */
    958     public void test_getPath() {
    959         String base = System.getProperty("user.home");
    960         String fname;
    961         File f1;
    962         if (!base.regionMatches((base.length() - 1), File.separator, 0, 1)) {
    963             base += File.separator;
    964         }
    965         fname = base + "filechk.tst";
    966         f1 = new File(base, "filechk.tst");
    967         File f2 = new File("filechk.tst");
    968         File f3 = new File("c:");
    969         File f4 = new File(base + "a" + File.separator + File.separator + ".." + File.separator
    970                 + "filechk.tst");
    971         assertEquals("getPath returned incorrect path(f1)",
    972                 fname, f1.getPath());
    973         assertEquals("getPath returned incorrect path(f2)",
    974                 "filechk.tst", f2.getPath());
    975         assertEquals("getPath returned incorrect path(f3)", "c:", f3.getPath());
    976         assertEquals("getPath returned incorrect path(f4)",
    977                 base + "a" + File.separator + ".." + File.separator + "filechk.tst",
    978                 f4.getPath());
    979         f1.delete();
    980         f2.delete();
    981         f3.delete();
    982         f4.delete();
    983 
    984         // Regression for HARMONY-444
    985         File file;
    986         String separator = File.separator;
    987 
    988         file = new File((File) null, "x/y/z");
    989         assertEquals("x" + separator + "y" + separator + "z", file.getPath());
    990 
    991         file = new File((String) null, "x/y/z");
    992         assertEquals("x" + separator + "y" + separator + "z", file.getPath());
    993 
    994         // Regression for HARMONY-829
    995         String f1ParentName = "01";
    996         f1 = new File(f1ParentName, "");
    997         assertEquals(f1ParentName, f1.getPath());
    998 
    999         String f2ParentName = "0";
   1000         f2 = new File(f2ParentName, "");
   1001 
   1002         assertEquals(-1, f2.compareTo(f1));
   1003         assertEquals(1, f1.compareTo(f2));
   1004 
   1005         File parent = tempDirectory;
   1006         f3 = new File(parent, "");
   1007 
   1008         assertEquals(parent.getPath(), f3.getPath());
   1009 
   1010         File file0 = new File("");
   1011         assertEquals("", file0.getPath());
   1012 
   1013         // Regression for HARMONY-3869
   1014         // Behavior here is system-dependent according to the RI javadoc.
   1015         String path1 = new File("", "").getPath();
   1016         assertTrue(path1.equals(File.separator) || path1.isEmpty());
   1017         String path2 = new File(new File(""), "").getPath();
   1018         assertTrue(path2.equals(File.separator) || path2.isEmpty());
   1019     }
   1020 
   1021     /**
   1022      * java.io.File#hashCode()
   1023      */
   1024     public void test_hashCode() {
   1025         // Regression for HARMONY-53
   1026         File mfile = new File("SoMe FiLeNaMe"); // Mixed case
   1027         File lfile = new File("some filename"); // Lower case
   1028 
   1029         if (mfile.equals(lfile)) {
   1030             assertTrue("Assert 0: wrong hashcode", mfile.hashCode() == lfile
   1031                     .hashCode());
   1032         } else {
   1033             assertFalse("Assert 1: wrong hashcode", mfile.hashCode() == lfile
   1034                     .hashCode());
   1035         }
   1036     }
   1037 
   1038     /**
   1039      * java.io.File#isAbsolute()
   1040      */
   1041     public void test_isAbsolute() {
   1042         if (File.separatorChar == '\\') {
   1043             File f = new File("c:\\test");
   1044             File f1 = new File("\\test");
   1045             // One or the other should be absolute on Windows or CE
   1046             assertTrue("Absolute returned false", (f.isAbsolute() && !f1
   1047                     .isAbsolute())
   1048                     || (!f.isAbsolute() && f1.isAbsolute()));
   1049 
   1050             assertTrue(new File("C:/").isAbsolute());
   1051             assertTrue(new File("f:/").isAbsolute());
   1052             assertTrue(new File("f:\\").isAbsolute());
   1053             assertFalse(new File("f:").isAbsolute());
   1054             assertFalse(new File("K:").isAbsolute());
   1055             assertTrue(new File("\\\\").isAbsolute());
   1056             assertTrue(new File("\\\\\\").isAbsolute());
   1057             assertTrue(new File("\\\\hello").isAbsolute());
   1058             assertFalse(new File("\\").isAbsolute());
   1059             assertFalse(new File("/").isAbsolute());
   1060         } else {
   1061             File f = new File("/test");
   1062             File f1 = new File("\\test");
   1063             assertTrue("Absolute returned false", f.isAbsolute());
   1064             assertFalse("Absolute returned true", f1.isAbsolute());
   1065             assertTrue(new File("//test").isAbsolute());
   1066             assertFalse(new File("test").isAbsolute());
   1067             assertFalse(new File("c:/").isAbsolute());
   1068             assertFalse(new File("c:\\").isAbsolute());
   1069             assertFalse(new File("c:").isAbsolute());
   1070             assertFalse(new File("\\").isAbsolute());
   1071             assertFalse(new File("\\\\").isAbsolute());
   1072         }
   1073         assertTrue("Non-Absolute returned true", !new File("../test")
   1074                 .isAbsolute());
   1075     }
   1076 
   1077     /**
   1078      * java.io.File#isDirectory()
   1079      */
   1080     public void test_isDirectory() {
   1081         String base = addTrailingSlash(tempDirectory.getPath());
   1082         File f = new File(base);
   1083         assertTrue("Test 1: Directory Returned False", f.isDirectory());
   1084         f = new File(base + "zxzxzxz" + platformId);
   1085         assertTrue("Test 2: (Not Created) Directory Returned True.", !f
   1086                 .isDirectory());
   1087         f.mkdir();
   1088         try {
   1089             assertTrue("Test 3: Directory Returned False.", f.isDirectory());
   1090         } finally {
   1091             f.delete();
   1092         }
   1093     }
   1094 
   1095     /**
   1096      * java.io.File#isFile()
   1097      */
   1098     public void test_isFile() throws IOException {
   1099         String base = tempDirectory.getPath();
   1100         File f = new File(base);
   1101         assertFalse("Directory Returned True As Being A File.", f.isFile());
   1102 
   1103         base = addTrailingSlash(base);
   1104         f = new File(base, platformId + "amiafile");
   1105         assertTrue("Non-existent File Returned True", !f.isFile());
   1106         FileOutputStream fos = new FileOutputStream(f);
   1107         fos.close();
   1108         assertTrue("File returned false", f.isFile());
   1109         f.delete();
   1110     }
   1111 
   1112     public void test_isHidden() throws IOException, InterruptedException {
   1113         boolean onUnix = File.separatorChar == '/';
   1114         assertTrue(onUnix);
   1115 
   1116         // On Unix hidden files are marked with a "." at the beginning
   1117         // of the file name.
   1118         File f1 = File.createTempFile("harmony-test-FileTest_notHidden_", ".tmp");
   1119         File f2 = File.createTempFile(".harmony-test-FileTest_isHidden_", ".tmp");
   1120         assertFalse(f1.isHidden());
   1121         assertTrue(f2.isHidden());
   1122         // We can still delete hidden files.
   1123         assertTrue(f2.delete());
   1124         f1.delete();
   1125     }
   1126 
   1127     /**
   1128      * java.io.File#lastModified()
   1129      */
   1130     public void test_lastModified() throws IOException {
   1131         File f = new File(System.getProperty("java.io.tmpdir"), platformId
   1132                 + "lModTest.tst");
   1133         f.delete();
   1134         long lastModifiedTime = f.lastModified();
   1135         assertEquals("LastModified Time Should Have Returned 0.", 0,
   1136                 lastModifiedTime);
   1137         FileOutputStream fos = new FileOutputStream(f);
   1138         fos.close();
   1139         f.setLastModified(315550800000L);
   1140         lastModifiedTime = f.lastModified();
   1141         assertEquals("LastModified Time Incorrect",
   1142                 315550800000L, lastModifiedTime);
   1143         f.delete();
   1144 
   1145         // Regression for HARMONY-2146
   1146         f = new File("/../");
   1147         assertTrue(f.lastModified() > 0);
   1148     }
   1149 
   1150     /**
   1151      * java.io.File#length()
   1152      */
   1153     public void test_length() throws IOException {
   1154         File f = new File(tempDirectory, platformId
   1155                 + "input.tst");
   1156         assertEquals("File Length Should Have Returned 0.", 0, f.length());
   1157         FileOutputStream fos = new FileOutputStream(f);
   1158         fos.write(fileString.getBytes());
   1159         fos.close();
   1160         assertEquals("Incorrect file length returned",
   1161                 fileString.length(), f.length());
   1162         f.delete();
   1163 
   1164         // regression test for HARMONY-1497
   1165         f = File.createTempFile("test", "tmp");
   1166         f.deleteOnExit();
   1167         RandomAccessFile raf = new RandomAccessFile(f, "rwd");
   1168         raf.write(0x41);
   1169         assertEquals(1, f.length());
   1170     }
   1171 
   1172     /**
   1173      * java.io.File#list()
   1174      */
   1175     public void test_list() throws IOException {
   1176         String base = tempDirectory.getPath();
   1177         // Old test left behind "garbage files" so this time it creates a
   1178         // directory that is guaranteed not to already exist (and deletes it
   1179         // afterward.)
   1180         int dirNumber = 1;
   1181         boolean dirExists = true;
   1182         File dir = null;
   1183         dir = new File(base, platformId + String.valueOf(dirNumber));
   1184         while (dirExists) {
   1185             if (dir.exists()) {
   1186                 dirNumber++;
   1187                 dir = new File(base, String.valueOf(dirNumber));
   1188             } else {
   1189                 dirExists = false;
   1190             }
   1191         }
   1192 
   1193         String[] flist = dir.list();
   1194 
   1195         assertNull("Method list() Should Have Returned null.", flist);
   1196 
   1197         assertTrue("Could not create parent directory for list test", dir
   1198                 .mkdir());
   1199 
   1200         String[] files = { "mtzz1.xx", "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" };
   1201         try {
   1202             assertEquals(
   1203                     "Method list() Should Have Returned An Array Of Length 0.",
   1204                     0, dir.list().length);
   1205 
   1206             File file = new File(dir, "notADir.tst");
   1207             try {
   1208                 FileOutputStream fos = new FileOutputStream(file);
   1209                 fos.close();
   1210                 assertNull(
   1211                         "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
   1212                         file.list());
   1213             } finally {
   1214                 file.delete();
   1215             }
   1216 
   1217             for (int i = 0; i < files.length; i++) {
   1218                 File f = new File(dir, files[i]);
   1219                 FileOutputStream fos = new FileOutputStream(f);
   1220                 fos.close();
   1221             }
   1222 
   1223             flist = dir.list();
   1224             if (flist.length != files.length) {
   1225                 fail("Incorrect list returned");
   1226             }
   1227 
   1228             // Checking to make sure the correct files were are listed in the
   1229             // array.
   1230             boolean[] check = new boolean[flist.length];
   1231             for (int i = 0; i < check.length; i++) {
   1232                 check[i] = false;
   1233             }
   1234             for (int i = 0; i < files.length; i++) {
   1235                 for (int j = 0; j < flist.length; j++) {
   1236                     if (flist[j].equals(files[i])) {
   1237                         check[i] = true;
   1238                         break;
   1239                     }
   1240                 }
   1241             }
   1242             int checkCount = 0;
   1243             for (int i = 0; i < check.length; i++) {
   1244                 if (check[i] == false) {
   1245                     checkCount++;
   1246                 }
   1247             }
   1248             assertEquals("Invalid file returned in listing", 0, checkCount);
   1249 
   1250             for (int i = 0; i < files.length; i++) {
   1251                 File f = new File(dir, files[i]);
   1252                 f.delete();
   1253             }
   1254 
   1255             assertTrue("Could not delete parent directory for list test.", dir
   1256                     .delete());
   1257         } finally {
   1258             for (int i = 0; i < files.length; i++) {
   1259                 File f = new File(dir, files[i]);
   1260                 f.delete();
   1261             }
   1262             dir.delete();
   1263         }
   1264     }
   1265 
   1266     /**
   1267      * java.io.File#listFiles()
   1268      */
   1269     public void test_listFiles() throws IOException, InterruptedException {
   1270         String base = tempDirectory.getPath();
   1271         // Finding a non-existent directory to create.
   1272         int dirNumber = 1;
   1273         boolean dirExists = true;
   1274         File dir = new File(base, platformId + String.valueOf(dirNumber));
   1275         // Making sure that the directory does not exist.
   1276         while (dirExists) {
   1277             // If the directory exists, add one to the directory number
   1278             // (making it a new directory name.)
   1279             if (dir.exists()) {
   1280                 dirNumber++;
   1281                 dir = new File(base, String.valueOf(dirNumber));
   1282             } else {
   1283                 dirExists = false;
   1284             }
   1285         }
   1286         // Test for attempting to call listFiles on a non-existent directory.
   1287         assertNull("listFiles Should Return Null.", dir.listFiles());
   1288 
   1289         assertTrue("Failed To Create Parent Directory.", dir.mkdir());
   1290 
   1291         String[] files = { "1.tst", "2.tst", "3.tst", "" };
   1292         try {
   1293             assertEquals("listFiles Should Return An Array Of Length 0.", 0,
   1294                     dir.listFiles().length);
   1295 
   1296             File file = new File(dir, "notADir.tst");
   1297             try {
   1298                 FileOutputStream fos = new FileOutputStream(file);
   1299                 fos.close();
   1300                 assertNull(
   1301                         "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
   1302                         file.listFiles());
   1303             } finally {
   1304                 file.delete();
   1305             }
   1306 
   1307             for (int i = 0; i < (files.length - 1); i++) {
   1308                 File f = new File(dir, files[i]);
   1309                 FileOutputStream fos = new FileOutputStream(f);
   1310                 fos.close();
   1311             }
   1312 
   1313             new File(dir, "doesNotExist.tst");
   1314             File[] flist = dir.listFiles();
   1315 
   1316             // Test to make sure that only the 3 files that were created are
   1317             // listed.
   1318             assertEquals("Incorrect Number Of Files Returned.", 3, flist.length);
   1319 
   1320             // Test to make sure that listFiles can read hidden files.
   1321             boolean onUnix = File.separatorChar == '/';
   1322             boolean onWindows = File.separatorChar == '\\';
   1323             if (onWindows) {
   1324                 files[3] = "4.tst";
   1325                 File f = new File(dir, "4.tst");
   1326                 FileOutputStream fos = new FileOutputStream(f);
   1327                 fos.close();
   1328                 Runtime r = Runtime.getRuntime();
   1329                 Process p = r.exec("attrib +h \"" + f.getPath() + "\"");
   1330                 p.waitFor();
   1331             }
   1332             if (onUnix) {
   1333                 files[3] = ".4.tst";
   1334                 File f = new File(dir, ".4.tst");
   1335                 FileOutputStream fos = new FileOutputStream(f);
   1336                 fos.close();
   1337             }
   1338             flist = dir.listFiles();
   1339             assertEquals("Incorrect Number Of Files Returned.", 4, flist.length);
   1340 
   1341             // Checking to make sure the correct files were are listed in
   1342             // the array.
   1343             boolean[] check = new boolean[flist.length];
   1344             for (int i = 0; i < check.length; i++) {
   1345                 check[i] = false;
   1346             }
   1347             for (int i = 0; i < files.length; i++) {
   1348                 for (int j = 0; j < flist.length; j++) {
   1349                     if (flist[j].getName().equals(files[i])) {
   1350                         check[i] = true;
   1351                         break;
   1352                     }
   1353                 }
   1354             }
   1355             int checkCount = 0;
   1356             for (int i = 0; i < check.length; i++) {
   1357                 if (check[i] == false) {
   1358                     checkCount++;
   1359                 }
   1360             }
   1361             assertEquals("Invalid file returned in listing", 0, checkCount);
   1362 
   1363             if (onWindows) {
   1364                 Runtime r = Runtime.getRuntime();
   1365                 Process p = r.exec("attrib -h \""
   1366                         + new File(dir, files[3]).getPath() + "\"");
   1367                 p.waitFor();
   1368             }
   1369 
   1370             for (int i = 0; i < files.length; i++) {
   1371                 File f = new File(dir, files[i]);
   1372                 f.delete();
   1373             }
   1374             assertTrue("Parent Directory Not Deleted.", dir.delete());
   1375         } finally {
   1376             for (int i = 0; i < files.length; i++) {
   1377                 File f = new File(dir, files[i]);
   1378                 f.delete();
   1379             }
   1380             dir.delete();
   1381         }
   1382     }
   1383 
   1384     /**
   1385      * java.io.File#listFiles(java.io.FileFilter)
   1386      */
   1387     public void test_listFilesLjava_io_FileFilter() throws IOException {
   1388         String base = System.getProperty("java.io.tmpdir");
   1389         // Finding a non-existent directory to create.
   1390         int dirNumber = 1;
   1391         boolean dirExists = true;
   1392         File baseDir = new File(base, platformId + String.valueOf(dirNumber));
   1393         // Making sure that the directory does not exist.
   1394         while (dirExists) {
   1395             // If the directory exists, add one to the directory number (making
   1396             // it a new directory name.)
   1397             if (baseDir.exists()) {
   1398                 dirNumber++;
   1399                 baseDir = new File(base, String.valueOf(dirNumber));
   1400             } else {
   1401                 dirExists = false;
   1402             }
   1403         }
   1404 
   1405         // Creating a filter that catches directories.
   1406         FileFilter dirFilter = new FileFilter() {
   1407             public boolean accept(File f) {
   1408                 return f.isDirectory();
   1409             }
   1410         };
   1411 
   1412         assertNull("listFiles Should Return Null.", baseDir
   1413                 .listFiles(dirFilter));
   1414 
   1415         assertTrue("Failed To Create Parent Directory.", baseDir.mkdir());
   1416 
   1417         File dir1 = null;
   1418         String[] files = { "1.tst", "2.tst", "3.tst" };
   1419         try {
   1420             assertEquals("listFiles Should Return An Array Of Length 0.", 0,
   1421                     baseDir.listFiles(dirFilter).length);
   1422 
   1423             File file = new File(baseDir, "notADir.tst");
   1424             try {
   1425                 FileOutputStream fos = new FileOutputStream(file);
   1426                 fos.close();
   1427                 assertNull(
   1428                         "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
   1429                         file.listFiles(dirFilter));
   1430             } finally {
   1431                 file.delete();
   1432             }
   1433 
   1434             for (int i = 0; i < files.length; i++) {
   1435                 File f = new File(baseDir, files[i]);
   1436                 FileOutputStream fos = new FileOutputStream(f);
   1437                 fos.close();
   1438             }
   1439             dir1 = new File(baseDir, "Temp1");
   1440             dir1.mkdir();
   1441 
   1442             // Creating a filter that catches files.
   1443             FileFilter fileFilter = new FileFilter() {
   1444                 public boolean accept(File f) {
   1445                     return f.isFile();
   1446                 }
   1447             };
   1448 
   1449             // Test to see if the correct number of directories are returned.
   1450             File[] directories = baseDir.listFiles(dirFilter);
   1451             assertEquals("Incorrect Number Of Directories Returned.", 1,
   1452                     directories.length);
   1453 
   1454             // Test to see if the directory was saved with the correct name.
   1455             assertEquals("Incorrect Directory Returned.", 0, directories[0]
   1456                     .compareTo(dir1));
   1457 
   1458             // Test to see if the correct number of files are returned.
   1459             File[] flist = baseDir.listFiles(fileFilter);
   1460             assertEquals("Incorrect Number Of Files Returned.",
   1461                     files.length, flist.length);
   1462 
   1463             // Checking to make sure the correct files were are listed in the
   1464             // array.
   1465             boolean[] check = new boolean[flist.length];
   1466             for (int i = 0; i < check.length; i++) {
   1467                 check[i] = false;
   1468             }
   1469             for (int i = 0; i < files.length; i++) {
   1470                 for (int j = 0; j < flist.length; j++) {
   1471                     if (flist[j].getName().equals(files[i])) {
   1472                         check[i] = true;
   1473                         break;
   1474                     }
   1475                 }
   1476             }
   1477             int checkCount = 0;
   1478             for (int i = 0; i < check.length; i++) {
   1479                 if (check[i] == false) {
   1480                     checkCount++;
   1481                 }
   1482             }
   1483             assertEquals("Invalid file returned in listing", 0, checkCount);
   1484 
   1485             for (int i = 0; i < files.length; i++) {
   1486                 File f = new File(baseDir, files[i]);
   1487                 f.delete();
   1488             }
   1489             dir1.delete();
   1490             assertTrue("Parent Directory Not Deleted.", baseDir.delete());
   1491         } finally {
   1492             for (int i = 0; i < files.length; i++) {
   1493                 File f = new File(baseDir, files[i]);
   1494                 f.delete();
   1495             }
   1496             if (dir1 != null) {
   1497                 dir1.delete();
   1498             }
   1499             baseDir.delete();
   1500         }
   1501     }
   1502 
   1503     /**
   1504      * java.io.File#listFiles(java.io.FilenameFilter)
   1505      */
   1506     public void test_listFilesLjava_io_FilenameFilter() throws IOException {
   1507         String base = System.getProperty("java.io.tmpdir");
   1508         // Finding a non-existent directory to create.
   1509         int dirNumber = 1;
   1510         boolean dirExists = true;
   1511         File dir = new File(base, platformId + String.valueOf(dirNumber));
   1512         // Making sure that the directory does not exist.
   1513         while (dirExists) {
   1514             // If the directory exists, add one to the directory number (making
   1515             // it a new directory name.)
   1516             if (dir.exists()) {
   1517                 dirNumber++;
   1518                 dir = new File(base, platformId + String.valueOf(dirNumber));
   1519             } else {
   1520                 dirExists = false;
   1521             }
   1522         }
   1523 
   1524         // Creating a filter that catches "*.tst" files.
   1525         FilenameFilter tstFilter = new FilenameFilter() {
   1526             public boolean accept(File f, String fileName) {
   1527                 return fileName.endsWith(".tst");
   1528             }
   1529         };
   1530 
   1531         assertNull("listFiles Should Return Null.", dir.listFiles(tstFilter));
   1532 
   1533         assertTrue("Failed To Create Parent Directory.", dir.mkdir());
   1534 
   1535         String[] files = { "1.tst", "2.tst", "3.tmp" };
   1536         try {
   1537             assertEquals("listFiles Should Return An Array Of Length 0.", 0,
   1538                     dir.listFiles(tstFilter).length);
   1539 
   1540             File file = new File(dir, "notADir.tst");
   1541             try {
   1542                 FileOutputStream fos = new FileOutputStream(file);
   1543                 fos.close();
   1544                 assertNull(
   1545                         "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
   1546                         file.listFiles(tstFilter));
   1547             } finally {
   1548                 file.delete();
   1549             }
   1550 
   1551             for (int i = 0; i < files.length; i++) {
   1552                 File f = new File(dir, files[i]);
   1553                 FileOutputStream fos = new FileOutputStream(f);
   1554                 fos.close();
   1555             }
   1556 
   1557             // Creating a filter that catches "*.tmp" files.
   1558             FilenameFilter tmpFilter = new FilenameFilter() {
   1559                 public boolean accept(File f, String fileName) {
   1560                     // If the suffix is ".tmp" then send it to the array
   1561                     if (fileName.endsWith(".tmp")) {
   1562                         return true;
   1563                     } else {
   1564                         return false;
   1565                     }
   1566                 }
   1567             };
   1568 
   1569             // Tests to see if the correct number of files were returned.
   1570             File[] flist = dir.listFiles(tstFilter);
   1571             assertEquals("Incorrect Number Of Files Passed Through tstFilter.",
   1572                     2, flist.length);
   1573             for (int i = 0; i < flist.length; i++) {
   1574                 assertTrue("File Should Not Have Passed The tstFilter.",
   1575                         flist[i].getPath().endsWith(".tst"));
   1576             }
   1577 
   1578             flist = dir.listFiles(tmpFilter);
   1579             assertEquals("Incorrect Number Of Files Passed Through tmpFilter.",
   1580                     1, flist.length);
   1581             assertTrue("File Should Not Have Passed The tmpFilter.", flist[0]
   1582                     .getPath().endsWith(".tmp"));
   1583 
   1584             for (int i = 0; i < files.length; i++) {
   1585                 File f = new File(dir, files[i]);
   1586                 f.delete();
   1587             }
   1588             assertTrue("Parent Directory Not Deleted.", dir.delete());
   1589         } finally {
   1590             for (int i = 0; i < files.length; i++) {
   1591                 File f = new File(dir, files[i]);
   1592                 f.delete();
   1593             }
   1594             dir.delete();
   1595         }
   1596     }
   1597 
   1598     /**
   1599      * java.io.File#list(java.io.FilenameFilter)
   1600      */
   1601     public void test_listLjava_io_FilenameFilter() throws IOException {
   1602         String base = tempDirectory.getPath();
   1603         // Old test left behind "garbage files" so this time it creates a
   1604         // directory that is guaranteed not to already exist (and deletes it
   1605         // afterward.)
   1606         int dirNumber = 1;
   1607         boolean dirExists = true;
   1608         File dir = new File(base, platformId + String.valueOf(dirNumber));
   1609         while (dirExists) {
   1610             if (dir.exists()) {
   1611                 dirNumber++;
   1612                 dir = new File(base, String.valueOf(dirNumber));
   1613             } else {
   1614                 dirExists = false;
   1615             }
   1616         }
   1617 
   1618         FilenameFilter filter = new FilenameFilter() {
   1619             public boolean accept(File dir, String name) {
   1620                 return !name.equals("mtzz1.xx");
   1621             }
   1622         };
   1623 
   1624         String[] flist = dir.list(filter);
   1625         assertNull("Method list(FilenameFilter) Should Have Returned Null.",
   1626                 flist);
   1627 
   1628         assertTrue("Could not create parent directory for test", dir.mkdir());
   1629 
   1630         String[] files = { "mtzz1.xx", "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" };
   1631         try {
   1632             /*
   1633              * Do not return null when trying to use list(Filename Filter) on a
   1634              * file rather than a directory. All other "list" methods return
   1635              * null for this test case.
   1636              */
   1637             /*
   1638              * File file = new File(dir, "notADir.tst"); try { FileOutputStream
   1639              * fos = new FileOutputStream(file); fos.close(); } catch
   1640              * (IOException e) { fail("Unexpected IOException During Test."); }
   1641              * flist = dir.list(filter); assertNull("listFiles Should Have
   1642              * Returned Null When Used On A File Instead Of A Directory.",
   1643              * flist); file.delete();
   1644              */
   1645 
   1646             flist = dir.list(filter);
   1647             assertEquals("Array Of Length 0 Should Have Returned.", 0,
   1648                     flist.length);
   1649 
   1650             for (int i = 0; i < files.length; i++) {
   1651                 File f = new File(dir, files[i]);
   1652                 FileOutputStream fos = new FileOutputStream(f);
   1653                 fos.close();
   1654             }
   1655 
   1656             flist = dir.list(filter);
   1657 
   1658             assertEquals("Incorrect list returned", flist.length,
   1659                     files.length - 1);
   1660 
   1661             // Checking to make sure the correct files were are listed in the
   1662             // array.
   1663             boolean[] check = new boolean[flist.length];
   1664             for (int i = 0; i < check.length; i++) {
   1665                 check[i] = false;
   1666             }
   1667             String[] wantedFiles = { "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" };
   1668             for (int i = 0; i < wantedFiles.length; i++) {
   1669                 for (int j = 0; j < flist.length; j++) {
   1670                     if (flist[j].equals(wantedFiles[i])) {
   1671                         check[i] = true;
   1672                         break;
   1673                     }
   1674                 }
   1675             }
   1676             int checkCount = 0;
   1677             for (int i = 0; i < check.length; i++) {
   1678                 if (check[i] == false) {
   1679                     checkCount++;
   1680                 }
   1681             }
   1682             assertEquals("Invalid file returned in listing", 0, checkCount);
   1683 
   1684             for (int i = 0; i < files.length; i++) {
   1685                 File f = new File(dir, files[i]);
   1686                 f.delete();
   1687             }
   1688             assertTrue("Could not delete parent directory for test.", dir
   1689                     .delete());
   1690         } finally {
   1691             for (int i = 0; i < files.length; i++) {
   1692                 File f = new File(dir, files[i]);
   1693                 f.delete();
   1694             }
   1695             dir.delete();
   1696         }
   1697     }
   1698 
   1699     /**
   1700      * java.io.File#listRoots()
   1701      */
   1702     public void test_listRoots() {
   1703         File[] roots = File.listRoots();
   1704         boolean onUnix = File.separatorChar == '/';
   1705         boolean onWindows = File.separatorChar == '\\';
   1706         if (onUnix) {
   1707             assertEquals("Incorrect Number Of Root Directories.", 1,
   1708                     roots.length);
   1709             String fileLoc = roots[0].getPath();
   1710             assertTrue("Incorrect Root Directory Returned.", fileLoc
   1711                     .startsWith(File.separator));
   1712         } else if (onWindows) {
   1713             // Need better test for Windows
   1714             assertTrue("Incorrect Number Of Root Directories.",
   1715                     roots.length > 0);
   1716         }
   1717     }
   1718 
   1719     /**
   1720      * java.io.File#mkdir()
   1721      */
   1722     public void test_mkdir() throws IOException {
   1723         String base = tempDirectory.getPath();
   1724         // Old test left behind "garbage files" so this time it creates a
   1725         // directory that is guaranteed not to already exist (and deletes it
   1726         // afterward.)
   1727         int dirNumber = 1;
   1728         boolean dirExists = true;
   1729         File dir = new File(base, String.valueOf(dirNumber));
   1730         while (dirExists) {
   1731             if (dir.exists()) {
   1732                 dirNumber++;
   1733                 dir = new File(base, String.valueOf(dirNumber));
   1734             } else {
   1735                 dirExists = false;
   1736             }
   1737         }
   1738 
   1739         assertTrue("mkdir failed", dir.mkdir());
   1740         assertTrue("mkdir worked but exists check failed", dir.exists());
   1741         dir.deleteOnExit();
   1742 
   1743         String longDirName = "abcdefghijklmnopqrstuvwx";// 24 chars
   1744         String newbase = new String(dir + File.separator);
   1745         StringBuilder sb = new StringBuilder(dir + File.separator);
   1746         StringBuilder sb2 = new StringBuilder(dir + File.separator);
   1747 
   1748         // Test make a long path
   1749         while (dir.getCanonicalPath().length() < 256 - longDirName.length()) {
   1750             sb.append(longDirName + File.separator);
   1751             dir = new File(sb.toString());
   1752             assertTrue("mkdir failed", dir.mkdir());
   1753             assertTrue("mkdir worked but exists check failed", dir.exists());
   1754             dir.deleteOnExit();
   1755         }
   1756 
   1757         while (dir.getCanonicalPath().length() < 256) {
   1758             sb.append(0);
   1759             dir = new File(sb.toString());
   1760             assertTrue("mkdir " + dir.getCanonicalPath().length() + " failed",
   1761                     dir.mkdir());
   1762             assertTrue("mkdir " + dir.getCanonicalPath().length()
   1763                     + " worked but exists check failed", dir.exists());
   1764             dir.deleteOnExit();
   1765         }
   1766         dir = new File(sb2.toString());
   1767         // Test make many paths
   1768         while (dir.getCanonicalPath().length() < 256) {
   1769             sb2.append(0);
   1770             dir = new File(sb2.toString());
   1771             assertTrue("mkdir " + dir.getCanonicalPath().length() + " failed",
   1772                     dir.mkdir());
   1773             assertTrue("mkdir " + dir.getCanonicalPath().length()
   1774                     + " worked but exists check failed", dir.exists());
   1775             dir.deleteOnExit();
   1776         }
   1777 
   1778         // Regression test for HARMONY-3656
   1779         String[] ss = { "dir\u3400", "abc", "abc@123", "!@#$%^&",
   1780                 "~\u4E00!\u4E8C@\u4E09$", "\u56DB\u4E94\u516D",
   1781                 "\u4E03\u516B\u4E5D" };
   1782         for (int i = 0; i < ss.length; i++) {
   1783             dir = new File(newbase, ss[i]);
   1784             assertTrue("mkdir " + dir.getCanonicalPath() + " failed",
   1785                     dir.mkdir());
   1786             assertTrue("mkdir " + dir.getCanonicalPath()
   1787                     + " worked but exists check failed",
   1788                     dir.exists());
   1789             dir.deleteOnExit();
   1790         }
   1791     }
   1792 
   1793     /**
   1794      * java.io.File#mkdir()
   1795      * <p/>
   1796      * HARMONY-6041
   1797      */
   1798     public void test_mkdir_special_unicode() throws IOException {
   1799         File specialDir = new File(this.tempDirectory, "\u5C73");
   1800         int i = 0;
   1801         while (specialDir.exists()) {
   1802             specialDir = new File("\u5C73" + i);
   1803             ++i;
   1804         }
   1805         assertFalse(specialDir.exists());
   1806         assertTrue(specialDir.mkdir());
   1807         assertTrue(specialDir.exists());
   1808     }
   1809 
   1810     /**
   1811      * java.io.File#mkdirs()
   1812      */
   1813     public void test_mkdirs() {
   1814         String userHome = addTrailingSlash(tempDirectory.getPath());
   1815         File f = new File(userHome + "mdtest" + platformId + File.separator + "mdtest2",
   1816                 "p.tst");
   1817         File g = new File(userHome + "mdtest" + platformId + File.separator + "mdtest2");
   1818         File h = new File(userHome + "mdtest" + platformId);
   1819         f.mkdirs();
   1820         try {
   1821             assertTrue("Base Directory not created", h.exists());
   1822             assertTrue("Directories not created", g.exists());
   1823             assertTrue("File not created", f.exists());
   1824         } finally {
   1825             f.delete();
   1826             g.delete();
   1827             h.delete();
   1828         }
   1829     }
   1830 
   1831     /**
   1832      * java.io.File#renameTo(java.io.File)
   1833      */
   1834     public void test_renameToLjava_io_File() throws IOException {
   1835         String base = tempDirectory.getPath();
   1836         File dir = new File(base, platformId);
   1837         dir.mkdir();
   1838         File f = new File(dir, "xxx.xxx");
   1839         File rfile = new File(dir, "yyy.yyy");
   1840         File f2 = new File(dir, "zzz.zzz");
   1841         try {
   1842             FileOutputStream fos = new FileOutputStream(f);
   1843             fos.write(fileString.getBytes());
   1844             fos.close();
   1845             long lengthOfFile = f.length();
   1846 
   1847             rfile.delete(); // in case it already exists
   1848 
   1849             assertTrue("Test 1: File Rename Failed", f.renameTo(rfile));
   1850             assertTrue("Test 2: File Rename Failed.", rfile.exists());
   1851             assertEquals("Test 3: Size Of File Changed.",
   1852                     lengthOfFile, rfile.length());
   1853 
   1854             fos = new FileOutputStream(rfile);
   1855             fos.close();
   1856 
   1857             f2.delete(); // in case it already exists
   1858             assertTrue("Test 4: File Rename Failed", rfile.renameTo(f2));
   1859             assertTrue("Test 5: File Rename Failed.", f2.exists());
   1860         } finally {
   1861             f.delete();
   1862             rfile.delete();
   1863             f2.delete();
   1864             dir.delete();
   1865         }
   1866     }
   1867 
   1868     /**
   1869      * java.io.File#setLastModified(long)
   1870      */
   1871     public void test_setLastModifiedJ() throws IOException {
   1872         File f1 = null;
   1873         try {
   1874             f1 = File.createTempFile("harmony-test-FileTest_setLastModified", ".tmp");
   1875             long orgTime = f1.lastModified();
   1876             // Subtracting 100 000 milliseconds from the orgTime of File f1
   1877             f1.setLastModified(orgTime - 100000);
   1878             long lastModified = f1.lastModified();
   1879             assertEquals("Test 1: LastModifed time incorrect",
   1880                     orgTime - 100000, lastModified);
   1881             // Subtracting 10 000 000 milliseconds from the orgTime of File f1
   1882             f1.setLastModified(orgTime - 10000000);
   1883             lastModified = f1.lastModified();
   1884             assertEquals("Test 2: LastModifed time incorrect",
   1885                     orgTime - 10000000, lastModified);
   1886             // Adding 100 000 milliseconds to the orgTime of File f1
   1887             f1.setLastModified(orgTime + 100000);
   1888             lastModified = f1.lastModified();
   1889             assertEquals("Test 3: LastModifed time incorrect",
   1890                     orgTime + 100000, lastModified);
   1891             // Adding 10 000 000 milliseconds from the orgTime of File f1
   1892             f1.setLastModified(orgTime + 10000000);
   1893             lastModified = f1.lastModified();
   1894             assertEquals("Test 4: LastModifed time incorrect",
   1895                     orgTime + 10000000, lastModified);
   1896             // Trying to set time to an exact number
   1897             f1.setLastModified(315550800000L);
   1898             lastModified = f1.lastModified();
   1899             assertEquals("Test 5: LastModified time incorrect",
   1900                     315550800000L, lastModified);
   1901             String osName = System.getProperty("os.name", "unknown");
   1902             if (osName.equals("Windows 2000") || osName.equals("Windows NT")) {
   1903                 // Trying to set time to a large exact number
   1904                 boolean result = f1.setLastModified(4354837199000L);
   1905                 long next = f1.lastModified();
   1906                 // Dec 31 23:59:59 EST 2107 is overflow on FAT file systems, and
   1907                 // the call fails
   1908                 if (result) {
   1909                     assertEquals("Test 6: LastModified time incorrect",
   1910                             4354837199000L, next);
   1911                 }
   1912             }
   1913             // Trying to set time to a negative number
   1914             try {
   1915                 f1.setLastModified(-25);
   1916                 fail("IllegalArgumentException Not Thrown.");
   1917             } catch (IllegalArgumentException e) {
   1918             }
   1919         } finally {
   1920             if (f1 != null) {
   1921                 f1.delete();
   1922             }
   1923         }
   1924     }
   1925 
   1926     /**
   1927      * java.io.File#setReadOnly()
   1928      */
   1929     public void test_setReadOnly() throws Exception {
   1930         File f1 = null;
   1931         File f2 = null;
   1932         if (Libcore.os.getuid() == 0) {
   1933             System.err.println("Skipping #test_setReadOnly: test runner is root");
   1934             return;
   1935         }
   1936 
   1937         try {
   1938             f1 = File.createTempFile("harmony-test-FileTest_setReadOnly", ".tmp");
   1939             f2 = File.createTempFile("harmony-test-FileTest_setReadOnly", ".tmp");
   1940             // Assert is flawed because canWrite does not work.
   1941             // assertTrue("File f1 Is Set To ReadOnly." , f1.canWrite());
   1942             assertTrue(f1.setReadOnly());
   1943             assertFalse(f1.canWrite());
   1944             // Assert is flawed because canWrite does not work.
   1945             // assertTrue("File f1 Is Not Set To ReadOnly." , !f1.canWrite());
   1946             try {
   1947                 // Attempt to write to a file that is setReadOnly.
   1948                 new FileOutputStream(f1);
   1949                 fail("IOException not thrown.");
   1950             } catch (IOException e) {
   1951                 // Expected
   1952             }
   1953 
   1954             Libcore.os.chmod(f1.getAbsolutePath(), 666);
   1955 
   1956             // Assert is flawed because canWrite does not work.
   1957             // assertTrue("File f1 Is Set To ReadOnly." , f1.canWrite());
   1958             FileOutputStream fos = new FileOutputStream(f1);
   1959             fos.write(fileString.getBytes());
   1960             fos.close();
   1961             assertEquals(fileString.length(), f1.length());
   1962             assertTrue(f1.delete());
   1963 
   1964             // Assert is flawed because canWrite does not work.
   1965             // assertTrue("File f2 Is Set To ReadOnly." , f2.canWrite());
   1966             fos = new FileOutputStream(f2);
   1967             // Write to a file.
   1968             fos.write(fileString.getBytes());
   1969             fos.close();
   1970             f2.setReadOnly();
   1971             // Assert is flawed because canWrite does not work.
   1972             // assertTrue("File f2 Is Not Set To ReadOnly." , !f2.canWrite());
   1973             try {
   1974                 // Attempt to write to a file that has previously been written
   1975                 // to.
   1976                 // and is now set to read only.
   1977                 fos = new FileOutputStream(f2);
   1978                 fail("IOException not thrown.");
   1979             } catch (IOException e) {
   1980                 // Expected
   1981             }
   1982 
   1983             Libcore.os.chmod(f2.getAbsolutePath(), 666);
   1984             assertTrue(f2.canWrite());
   1985             fos = new FileOutputStream(f2);
   1986             fos.write(fileString.getBytes());
   1987             fos.close();
   1988             f2.setReadOnly();
   1989             assertTrue(f2.delete());
   1990 
   1991             // Similarly, trying to delete a read-only directory should succeed
   1992             f2 = new File(tempDirectory, "deltestdir");
   1993             f2.mkdir();
   1994             f2.setReadOnly();
   1995             assertTrue("Directory f2 Did Not Delete", f2.delete());
   1996             assertTrue("Directory f2 Did Not Delete", !f2.exists());
   1997         } finally {
   1998             if (f1 != null) {
   1999                 f1.delete();
   2000             }
   2001             if (f2 != null) {
   2002                 f2.delete();
   2003             }
   2004         }
   2005     }
   2006 
   2007     /**
   2008      * java.io.File#toString()
   2009      */
   2010     public void test_toString() {
   2011         String fileName = System.getProperty("user.home");
   2012         if (!fileName.endsWith(File.separator)) {
   2013             fileName += File.separator;
   2014         }
   2015         fileName += "input.tst";
   2016         File f = new File(fileName);
   2017         assertEquals("Incorrect string returned", fileName, f.toString());
   2018 
   2019         if (File.separatorChar == '\\') {
   2020             String result = new File("c:\\").toString();
   2021             assertEquals("Removed backslash", "c:\\", result);
   2022         }
   2023     }
   2024 
   2025     /**
   2026      * java.io.File#toURI()
   2027      */
   2028     public void test_toURI() throws URISyntaxException {
   2029         // Need a directory that exists
   2030         File dir = tempDirectory;
   2031 
   2032         // Test for toURI when the file is a directory.
   2033         String newURIPath = dir.getAbsolutePath();
   2034         newURIPath = newURIPath.replace(File.separatorChar, '/');
   2035         if (!newURIPath.startsWith("/")) {
   2036             newURIPath = "/" + newURIPath;
   2037         }
   2038         if (!newURIPath.endsWith("/")) {
   2039             newURIPath += '/';
   2040         }
   2041 
   2042         URI uri = dir.toURI();
   2043         assertEquals("Test 1A: Incorrect URI Returned.", dir.getAbsoluteFile(), new File(uri));
   2044         assertEquals("Test 1B: Incorrect URI Returned.",
   2045                 new URI("file", null, newURIPath, null, null), uri);
   2046 
   2047         // Test for toURI with a file name with illegal chars.
   2048         File f = new File(dir, "te% \u20ac st.tst");
   2049         newURIPath = f.getAbsolutePath();
   2050         newURIPath = newURIPath.replace(File.separatorChar, '/');
   2051         if (!newURIPath.startsWith("/")) {
   2052             newURIPath = "/" + newURIPath;
   2053         }
   2054 
   2055         uri = f.toURI();
   2056         assertEquals("Test 2A: Incorrect URI Returned.",
   2057                 f.getAbsoluteFile(), new File(uri));
   2058         assertEquals("Test 2B: Incorrect URI Returned.",
   2059                 new URI("file", null, newURIPath, null, null), uri);
   2060 
   2061         // Regression test for HARMONY-3207
   2062         dir = new File(""); // current directory
   2063         uri = dir.toURI();
   2064         assertTrue("Test current dir: URI does not end with slash.", uri
   2065                 .toString().endsWith("/"));
   2066     }
   2067 
   2068     /**
   2069      * java.io.File#toURL()
   2070      */
   2071     public void test_toURL() throws MalformedURLException {
   2072         // Need a directory that exists
   2073         File dir = tempDirectory;
   2074 
   2075         // Test for toURL when the file is a directory.
   2076         String newDirURL = dir.getAbsolutePath();
   2077         newDirURL = newDirURL.replace(File.separatorChar, '/');
   2078         if (newDirURL.startsWith("/")) {
   2079             newDirURL = "file:" + newDirURL;
   2080         } else {
   2081             newDirURL = "file:/" + newDirURL;
   2082         }
   2083         if (!newDirURL.endsWith("/")) {
   2084             newDirURL += '/';
   2085         }
   2086         assertEquals("Test 1: Incorrect URL Returned.",
   2087                 dir.toURL().toString(), newDirURL);
   2088 
   2089         // Test for toURL with a file.
   2090         File f = new File(dir, "test.tst");
   2091         String newURL = f.getAbsolutePath();
   2092         newURL = newURL.replace(File.separatorChar, '/');
   2093         if (newURL.startsWith("/")) {
   2094             newURL = "file:" + newURL;
   2095         } else {
   2096             newURL = "file:/" + newURL;
   2097         }
   2098         assertEquals("Test 2: Incorrect URL Returned.",
   2099                 f.toURL().toString(), newURL);
   2100 
   2101         // Regression test for HARMONY-3207
   2102         dir = new File(""); // current directory
   2103         newDirURL = dir.toURL().toString();
   2104         assertTrue("Test current dir: URL does not end with slash.", newDirURL
   2105                 .endsWith("/"));
   2106     }
   2107 
   2108     /**
   2109      * java.io.File#toURI()
   2110      */
   2111     public void test_toURI2() throws URISyntaxException {
   2112         File f = new File(tempDirectory, "a/b/c/../d/e/./f");
   2113 
   2114         String path = f.getAbsolutePath();
   2115         path = path.replace(File.separatorChar, '/');
   2116         if (!path.startsWith("/")) {
   2117             path = "/" + path;
   2118         }
   2119 
   2120         URI uri1 = new URI("file", null, path, null);
   2121         URI uri2 = f.toURI();
   2122         assertEquals("uris not equal", uri1, uri2);
   2123     }
   2124 
   2125     /**
   2126      * java.io.File#toURL()
   2127      */
   2128     public void test_toURL2() throws MalformedURLException {
   2129         File f = new File(tempDirectory, "a/b/c/../d/e/./f");
   2130 
   2131         String path = f.getAbsolutePath();
   2132         path = path.replace(File.separatorChar, '/');
   2133         if (!path.startsWith("/")) {
   2134             path = "/" + path;
   2135         }
   2136 
   2137         URL url1 = new URL("file", "", path);
   2138         URL url2 = f.toURL();
   2139         assertEquals("urls not equal", url1, url2);
   2140     }
   2141 
   2142     /**
   2143      * serialization
   2144      */
   2145     public void test_objectStreamClass_getFields() throws Exception {
   2146         // Regression for HARMONY-2674
   2147         ObjectStreamClass objectStreamClass = ObjectStreamClass
   2148                 .lookup(File.class);
   2149         ObjectStreamField[] objectStreamFields = objectStreamClass.getFields();
   2150         assertEquals(1, objectStreamFields.length);
   2151         ObjectStreamField objectStreamField = objectStreamFields[0];
   2152         assertEquals("path", objectStreamField.getName());
   2153         assertEquals(String.class, objectStreamField.getType());
   2154     }
   2155 
   2156     // Regression test for HARMONY-4493
   2157     public void test_list_withUnicodeFileName() throws Exception {
   2158         File rootDir = new File(System.getProperty("java.io.tmpdir")).getAbsoluteFile();
   2159         String dirName = new String("src\u3400");
   2160         File dir = new File(rootDir, dirName);
   2161         if (!dir.exists()) {
   2162             dir.mkdir();
   2163             dir.deleteOnExit();
   2164         }
   2165         boolean exist = false;
   2166         String[] fileNames = rootDir.list();
   2167         for (String fileName : fileNames) {
   2168             if (dirName.equals(fileName)) {
   2169                 exist = true;
   2170                 break;
   2171             }
   2172         }
   2173         assertTrue(exist);
   2174     }
   2175 
   2176     /**
   2177      * serialization/deserialization.
   2178      */
   2179     public void test_serialization_self() throws Exception {
   2180         File testFile = new File("test.ser");
   2181         SerializationTest.verifySelf(testFile);
   2182     }
   2183 
   2184     /**
   2185      * serialization/deserialization compatibility with RI.
   2186      */
   2187     public void test_serialization_compatibility() throws Exception {
   2188         File file = new File("FileTest.golden.ser");
   2189         SerializationTest.verifyGolden(this, file);
   2190     }
   2191 }
   2192