• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
deleteTempFolder(File dir)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 
addTrailingSlash(String path)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 
setUp()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 
tearDown()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      */
test_ConstructorLjava_io_FileLjava_lang_String0()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 
test_ConstructorLjava_io_FileLjava_lang_String1()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 
test_ConstructorLjava_io_FileLjava_lang_String2()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 
test_ConstructorLjava_io_FileLjava_lang_String3()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 
test_ConstructorLjava_io_FileLjava_lang_String4()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 
test_ConstructorLjava_io_FileLjava_lang_String5()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 
test_ConstructorLjava_io_FileLjava_lang_String6()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      */
test_ConstructorLjava_lang_String()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      */
test_ConstructorLjava_lang_StringLjava_lang_String()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      */
test_Constructor_String_String_112270()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      */
test_Constructor_File_String_112270()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      */
test_ConstructorLjava_net_URI()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@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      */
test_canRead()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      */
test_canWrite()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      */
test_compareToLjava_io_File()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      */
test_createNewFile_EmptyString()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      */
test_createNewFile()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      */
test_createTempFileLjava_lang_StringLjava_lang_String()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      */
test_createTempFileLjava_lang_StringLjava_lang_StringLjava_io_File()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      */
test_delete()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      */
test_equalsLjava_lang_Object()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      */
test_exists()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      */
test_getAbsoluteFile()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      */
test_getAbsolutePath()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      */
test_getCanonicalFile()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      */
test_getCanonicalPath()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      */
test_getName()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      */
test_getParent()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      */
test_getParentFile()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      */
test_getPath()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      */
test_hashCode()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      */
test_isAbsolute()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      */
test_isDirectory()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      */
test_isFile()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 
test_isHidden()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      */
test_lastModified()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 
1146     /**
1147      * java.io.File#length()
1148      */
test_length()1149     public void test_length() throws IOException {
1150         File f = new File(tempDirectory, platformId
1151                 + "input.tst");
1152         assertEquals("File Length Should Have Returned 0.", 0, f.length());
1153         FileOutputStream fos = new FileOutputStream(f);
1154         fos.write(fileString.getBytes());
1155         fos.close();
1156         assertEquals("Incorrect file length returned",
1157                 fileString.length(), f.length());
1158         f.delete();
1159 
1160         // regression test for HARMONY-1497
1161         f = File.createTempFile("test", "tmp");
1162         f.deleteOnExit();
1163         RandomAccessFile raf = new RandomAccessFile(f, "rwd");
1164         raf.write(0x41);
1165         assertEquals(1, f.length());
1166     }
1167 
1168     /**
1169      * java.io.File#list()
1170      */
test_list()1171     public void test_list() throws IOException {
1172         String base = tempDirectory.getPath();
1173         // Old test left behind "garbage files" so this time it creates a
1174         // directory that is guaranteed not to already exist (and deletes it
1175         // afterward.)
1176         int dirNumber = 1;
1177         boolean dirExists = true;
1178         File dir = null;
1179         dir = new File(base, platformId + String.valueOf(dirNumber));
1180         while (dirExists) {
1181             if (dir.exists()) {
1182                 dirNumber++;
1183                 dir = new File(base, String.valueOf(dirNumber));
1184             } else {
1185                 dirExists = false;
1186             }
1187         }
1188 
1189         String[] flist = dir.list();
1190 
1191         assertNull("Method list() Should Have Returned null.", flist);
1192 
1193         assertTrue("Could not create parent directory for list test", dir
1194                 .mkdir());
1195 
1196         String[] files = { "mtzz1.xx", "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" };
1197         try {
1198             assertEquals(
1199                     "Method list() Should Have Returned An Array Of Length 0.",
1200                     0, dir.list().length);
1201 
1202             File file = new File(dir, "notADir.tst");
1203             try {
1204                 FileOutputStream fos = new FileOutputStream(file);
1205                 fos.close();
1206                 assertNull(
1207                         "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
1208                         file.list());
1209             } finally {
1210                 file.delete();
1211             }
1212 
1213             for (int i = 0; i < files.length; i++) {
1214                 File f = new File(dir, files[i]);
1215                 FileOutputStream fos = new FileOutputStream(f);
1216                 fos.close();
1217             }
1218 
1219             flist = dir.list();
1220             if (flist.length != files.length) {
1221                 fail("Incorrect list returned");
1222             }
1223 
1224             // Checking to make sure the correct files were are listed in the
1225             // array.
1226             boolean[] check = new boolean[flist.length];
1227             for (int i = 0; i < check.length; i++) {
1228                 check[i] = false;
1229             }
1230             for (int i = 0; i < files.length; i++) {
1231                 for (int j = 0; j < flist.length; j++) {
1232                     if (flist[j].equals(files[i])) {
1233                         check[i] = true;
1234                         break;
1235                     }
1236                 }
1237             }
1238             int checkCount = 0;
1239             for (int i = 0; i < check.length; i++) {
1240                 if (check[i] == false) {
1241                     checkCount++;
1242                 }
1243             }
1244             assertEquals("Invalid file returned in listing", 0, checkCount);
1245 
1246             for (int i = 0; i < files.length; i++) {
1247                 File f = new File(dir, files[i]);
1248                 f.delete();
1249             }
1250 
1251             assertTrue("Could not delete parent directory for list test.", dir
1252                     .delete());
1253         } finally {
1254             for (int i = 0; i < files.length; i++) {
1255                 File f = new File(dir, files[i]);
1256                 f.delete();
1257             }
1258             dir.delete();
1259         }
1260     }
1261 
1262     /**
1263      * java.io.File#listFiles()
1264      */
test_listFiles()1265     public void test_listFiles() throws IOException, InterruptedException {
1266         String base = tempDirectory.getPath();
1267         // Finding a non-existent directory to create.
1268         int dirNumber = 1;
1269         boolean dirExists = true;
1270         File dir = new File(base, platformId + String.valueOf(dirNumber));
1271         // Making sure that the directory does not exist.
1272         while (dirExists) {
1273             // If the directory exists, add one to the directory number
1274             // (making it a new directory name.)
1275             if (dir.exists()) {
1276                 dirNumber++;
1277                 dir = new File(base, String.valueOf(dirNumber));
1278             } else {
1279                 dirExists = false;
1280             }
1281         }
1282         // Test for attempting to call listFiles on a non-existent directory.
1283         assertNull("listFiles Should Return Null.", dir.listFiles());
1284 
1285         assertTrue("Failed To Create Parent Directory.", dir.mkdir());
1286 
1287         String[] files = { "1.tst", "2.tst", "3.tst", "" };
1288         try {
1289             assertEquals("listFiles Should Return An Array Of Length 0.", 0,
1290                     dir.listFiles().length);
1291 
1292             File file = new File(dir, "notADir.tst");
1293             try {
1294                 FileOutputStream fos = new FileOutputStream(file);
1295                 fos.close();
1296                 assertNull(
1297                         "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
1298                         file.listFiles());
1299             } finally {
1300                 file.delete();
1301             }
1302 
1303             for (int i = 0; i < (files.length - 1); i++) {
1304                 File f = new File(dir, files[i]);
1305                 FileOutputStream fos = new FileOutputStream(f);
1306                 fos.close();
1307             }
1308 
1309             new File(dir, "doesNotExist.tst");
1310             File[] flist = dir.listFiles();
1311 
1312             // Test to make sure that only the 3 files that were created are
1313             // listed.
1314             assertEquals("Incorrect Number Of Files Returned.", 3, flist.length);
1315 
1316             // Test to make sure that listFiles can read hidden files.
1317             boolean onUnix = File.separatorChar == '/';
1318             boolean onWindows = File.separatorChar == '\\';
1319             if (onWindows) {
1320                 files[3] = "4.tst";
1321                 File f = new File(dir, "4.tst");
1322                 FileOutputStream fos = new FileOutputStream(f);
1323                 fos.close();
1324                 Runtime r = Runtime.getRuntime();
1325                 Process p = r.exec("attrib +h \"" + f.getPath() + "\"");
1326                 p.waitFor();
1327             }
1328             if (onUnix) {
1329                 files[3] = ".4.tst";
1330                 File f = new File(dir, ".4.tst");
1331                 FileOutputStream fos = new FileOutputStream(f);
1332                 fos.close();
1333             }
1334             flist = dir.listFiles();
1335             assertEquals("Incorrect Number Of Files Returned.", 4, flist.length);
1336 
1337             // Checking to make sure the correct files were are listed in
1338             // the array.
1339             boolean[] check = new boolean[flist.length];
1340             for (int i = 0; i < check.length; i++) {
1341                 check[i] = false;
1342             }
1343             for (int i = 0; i < files.length; i++) {
1344                 for (int j = 0; j < flist.length; j++) {
1345                     if (flist[j].getName().equals(files[i])) {
1346                         check[i] = true;
1347                         break;
1348                     }
1349                 }
1350             }
1351             int checkCount = 0;
1352             for (int i = 0; i < check.length; i++) {
1353                 if (check[i] == false) {
1354                     checkCount++;
1355                 }
1356             }
1357             assertEquals("Invalid file returned in listing", 0, checkCount);
1358 
1359             if (onWindows) {
1360                 Runtime r = Runtime.getRuntime();
1361                 Process p = r.exec("attrib -h \""
1362                         + new File(dir, files[3]).getPath() + "\"");
1363                 p.waitFor();
1364             }
1365 
1366             for (int i = 0; i < files.length; i++) {
1367                 File f = new File(dir, files[i]);
1368                 f.delete();
1369             }
1370             assertTrue("Parent Directory Not Deleted.", dir.delete());
1371         } finally {
1372             for (int i = 0; i < files.length; i++) {
1373                 File f = new File(dir, files[i]);
1374                 f.delete();
1375             }
1376             dir.delete();
1377         }
1378     }
1379 
1380     /**
1381      * java.io.File#listFiles(java.io.FileFilter)
1382      */
test_listFilesLjava_io_FileFilter()1383     public void test_listFilesLjava_io_FileFilter() throws IOException {
1384         String base = System.getProperty("java.io.tmpdir");
1385         // Finding a non-existent directory to create.
1386         int dirNumber = 1;
1387         boolean dirExists = true;
1388         File baseDir = new File(base, platformId + String.valueOf(dirNumber));
1389         // Making sure that the directory does not exist.
1390         while (dirExists) {
1391             // If the directory exists, add one to the directory number (making
1392             // it a new directory name.)
1393             if (baseDir.exists()) {
1394                 dirNumber++;
1395                 baseDir = new File(base, String.valueOf(dirNumber));
1396             } else {
1397                 dirExists = false;
1398             }
1399         }
1400 
1401         // Creating a filter that catches directories.
1402         FileFilter dirFilter = new FileFilter() {
1403             public boolean accept(File f) {
1404                 return f.isDirectory();
1405             }
1406         };
1407 
1408         assertNull("listFiles Should Return Null.", baseDir
1409                 .listFiles(dirFilter));
1410 
1411         assertTrue("Failed To Create Parent Directory.", baseDir.mkdir());
1412 
1413         File dir1 = null;
1414         String[] files = { "1.tst", "2.tst", "3.tst" };
1415         try {
1416             assertEquals("listFiles Should Return An Array Of Length 0.", 0,
1417                     baseDir.listFiles(dirFilter).length);
1418 
1419             File file = new File(baseDir, "notADir.tst");
1420             try {
1421                 FileOutputStream fos = new FileOutputStream(file);
1422                 fos.close();
1423                 assertNull(
1424                         "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
1425                         file.listFiles(dirFilter));
1426             } finally {
1427                 file.delete();
1428             }
1429 
1430             for (int i = 0; i < files.length; i++) {
1431                 File f = new File(baseDir, files[i]);
1432                 FileOutputStream fos = new FileOutputStream(f);
1433                 fos.close();
1434             }
1435             dir1 = new File(baseDir, "Temp1");
1436             dir1.mkdir();
1437 
1438             // Creating a filter that catches files.
1439             FileFilter fileFilter = new FileFilter() {
1440                 public boolean accept(File f) {
1441                     return f.isFile();
1442                 }
1443             };
1444 
1445             // Test to see if the correct number of directories are returned.
1446             File[] directories = baseDir.listFiles(dirFilter);
1447             assertEquals("Incorrect Number Of Directories Returned.", 1,
1448                     directories.length);
1449 
1450             // Test to see if the directory was saved with the correct name.
1451             assertEquals("Incorrect Directory Returned.", 0, directories[0]
1452                     .compareTo(dir1));
1453 
1454             // Test to see if the correct number of files are returned.
1455             File[] flist = baseDir.listFiles(fileFilter);
1456             assertEquals("Incorrect Number Of Files Returned.",
1457                     files.length, flist.length);
1458 
1459             // Checking to make sure the correct files were are listed in the
1460             // array.
1461             boolean[] check = new boolean[flist.length];
1462             for (int i = 0; i < check.length; i++) {
1463                 check[i] = false;
1464             }
1465             for (int i = 0; i < files.length; i++) {
1466                 for (int j = 0; j < flist.length; j++) {
1467                     if (flist[j].getName().equals(files[i])) {
1468                         check[i] = true;
1469                         break;
1470                     }
1471                 }
1472             }
1473             int checkCount = 0;
1474             for (int i = 0; i < check.length; i++) {
1475                 if (check[i] == false) {
1476                     checkCount++;
1477                 }
1478             }
1479             assertEquals("Invalid file returned in listing", 0, checkCount);
1480 
1481             for (int i = 0; i < files.length; i++) {
1482                 File f = new File(baseDir, files[i]);
1483                 f.delete();
1484             }
1485             dir1.delete();
1486             assertTrue("Parent Directory Not Deleted.", baseDir.delete());
1487         } finally {
1488             for (int i = 0; i < files.length; i++) {
1489                 File f = new File(baseDir, files[i]);
1490                 f.delete();
1491             }
1492             if (dir1 != null) {
1493                 dir1.delete();
1494             }
1495             baseDir.delete();
1496         }
1497     }
1498 
1499     /**
1500      * java.io.File#listFiles(java.io.FilenameFilter)
1501      */
test_listFilesLjava_io_FilenameFilter()1502     public void test_listFilesLjava_io_FilenameFilter() throws IOException {
1503         String base = System.getProperty("java.io.tmpdir");
1504         // Finding a non-existent directory to create.
1505         int dirNumber = 1;
1506         boolean dirExists = true;
1507         File dir = new File(base, platformId + String.valueOf(dirNumber));
1508         // Making sure that the directory does not exist.
1509         while (dirExists) {
1510             // If the directory exists, add one to the directory number (making
1511             // it a new directory name.)
1512             if (dir.exists()) {
1513                 dirNumber++;
1514                 dir = new File(base, platformId + String.valueOf(dirNumber));
1515             } else {
1516                 dirExists = false;
1517             }
1518         }
1519 
1520         // Creating a filter that catches "*.tst" files.
1521         FilenameFilter tstFilter = new FilenameFilter() {
1522             public boolean accept(File f, String fileName) {
1523                 return fileName.endsWith(".tst");
1524             }
1525         };
1526 
1527         assertNull("listFiles Should Return Null.", dir.listFiles(tstFilter));
1528 
1529         assertTrue("Failed To Create Parent Directory.", dir.mkdir());
1530 
1531         String[] files = { "1.tst", "2.tst", "3.tmp" };
1532         try {
1533             assertEquals("listFiles Should Return An Array Of Length 0.", 0,
1534                     dir.listFiles(tstFilter).length);
1535 
1536             File file = new File(dir, "notADir.tst");
1537             try {
1538                 FileOutputStream fos = new FileOutputStream(file);
1539                 fos.close();
1540                 assertNull(
1541                         "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
1542                         file.listFiles(tstFilter));
1543             } finally {
1544                 file.delete();
1545             }
1546 
1547             for (int i = 0; i < files.length; i++) {
1548                 File f = new File(dir, files[i]);
1549                 FileOutputStream fos = new FileOutputStream(f);
1550                 fos.close();
1551             }
1552 
1553             // Creating a filter that catches "*.tmp" files.
1554             FilenameFilter tmpFilter = new FilenameFilter() {
1555                 public boolean accept(File f, String fileName) {
1556                     // If the suffix is ".tmp" then send it to the array
1557                     if (fileName.endsWith(".tmp")) {
1558                         return true;
1559                     } else {
1560                         return false;
1561                     }
1562                 }
1563             };
1564 
1565             // Tests to see if the correct number of files were returned.
1566             File[] flist = dir.listFiles(tstFilter);
1567             assertEquals("Incorrect Number Of Files Passed Through tstFilter.",
1568                     2, flist.length);
1569             for (int i = 0; i < flist.length; i++) {
1570                 assertTrue("File Should Not Have Passed The tstFilter.",
1571                         flist[i].getPath().endsWith(".tst"));
1572             }
1573 
1574             flist = dir.listFiles(tmpFilter);
1575             assertEquals("Incorrect Number Of Files Passed Through tmpFilter.",
1576                     1, flist.length);
1577             assertTrue("File Should Not Have Passed The tmpFilter.", flist[0]
1578                     .getPath().endsWith(".tmp"));
1579 
1580             for (int i = 0; i < files.length; i++) {
1581                 File f = new File(dir, files[i]);
1582                 f.delete();
1583             }
1584             assertTrue("Parent Directory Not Deleted.", dir.delete());
1585         } finally {
1586             for (int i = 0; i < files.length; i++) {
1587                 File f = new File(dir, files[i]);
1588                 f.delete();
1589             }
1590             dir.delete();
1591         }
1592     }
1593 
1594     /**
1595      * java.io.File#list(java.io.FilenameFilter)
1596      */
test_listLjava_io_FilenameFilter()1597     public void test_listLjava_io_FilenameFilter() throws IOException {
1598         String base = tempDirectory.getPath();
1599         // Old test left behind "garbage files" so this time it creates a
1600         // directory that is guaranteed not to already exist (and deletes it
1601         // afterward.)
1602         int dirNumber = 1;
1603         boolean dirExists = true;
1604         File dir = new File(base, platformId + String.valueOf(dirNumber));
1605         while (dirExists) {
1606             if (dir.exists()) {
1607                 dirNumber++;
1608                 dir = new File(base, String.valueOf(dirNumber));
1609             } else {
1610                 dirExists = false;
1611             }
1612         }
1613 
1614         FilenameFilter filter = new FilenameFilter() {
1615             public boolean accept(File dir, String name) {
1616                 return !name.equals("mtzz1.xx");
1617             }
1618         };
1619 
1620         String[] flist = dir.list(filter);
1621         assertNull("Method list(FilenameFilter) Should Have Returned Null.",
1622                 flist);
1623 
1624         assertTrue("Could not create parent directory for test", dir.mkdir());
1625 
1626         String[] files = { "mtzz1.xx", "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" };
1627         try {
1628             /*
1629              * Do not return null when trying to use list(Filename Filter) on a
1630              * file rather than a directory. All other "list" methods return
1631              * null for this test case.
1632              */
1633             /*
1634              * File file = new File(dir, "notADir.tst"); try { FileOutputStream
1635              * fos = new FileOutputStream(file); fos.close(); } catch
1636              * (IOException e) { fail("Unexpected IOException During Test."); }
1637              * flist = dir.list(filter); assertNull("listFiles Should Have
1638              * Returned Null When Used On A File Instead Of A Directory.",
1639              * flist); file.delete();
1640              */
1641 
1642             flist = dir.list(filter);
1643             assertEquals("Array Of Length 0 Should Have Returned.", 0,
1644                     flist.length);
1645 
1646             for (int i = 0; i < files.length; i++) {
1647                 File f = new File(dir, files[i]);
1648                 FileOutputStream fos = new FileOutputStream(f);
1649                 fos.close();
1650             }
1651 
1652             flist = dir.list(filter);
1653 
1654             assertEquals("Incorrect list returned", flist.length,
1655                     files.length - 1);
1656 
1657             // Checking to make sure the correct files were are listed in the
1658             // array.
1659             boolean[] check = new boolean[flist.length];
1660             for (int i = 0; i < check.length; i++) {
1661                 check[i] = false;
1662             }
1663             String[] wantedFiles = { "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" };
1664             for (int i = 0; i < wantedFiles.length; i++) {
1665                 for (int j = 0; j < flist.length; j++) {
1666                     if (flist[j].equals(wantedFiles[i])) {
1667                         check[i] = true;
1668                         break;
1669                     }
1670                 }
1671             }
1672             int checkCount = 0;
1673             for (int i = 0; i < check.length; i++) {
1674                 if (check[i] == false) {
1675                     checkCount++;
1676                 }
1677             }
1678             assertEquals("Invalid file returned in listing", 0, checkCount);
1679 
1680             for (int i = 0; i < files.length; i++) {
1681                 File f = new File(dir, files[i]);
1682                 f.delete();
1683             }
1684             assertTrue("Could not delete parent directory for test.", dir
1685                     .delete());
1686         } finally {
1687             for (int i = 0; i < files.length; i++) {
1688                 File f = new File(dir, files[i]);
1689                 f.delete();
1690             }
1691             dir.delete();
1692         }
1693     }
1694 
1695     /**
1696      * java.io.File#listRoots()
1697      */
test_listRoots()1698     public void test_listRoots() {
1699         File[] roots = File.listRoots();
1700         boolean onUnix = File.separatorChar == '/';
1701         boolean onWindows = File.separatorChar == '\\';
1702         if (onUnix) {
1703             assertEquals("Incorrect Number Of Root Directories.", 1,
1704                     roots.length);
1705             String fileLoc = roots[0].getPath();
1706             assertTrue("Incorrect Root Directory Returned.", fileLoc
1707                     .startsWith(File.separator));
1708         } else if (onWindows) {
1709             // Need better test for Windows
1710             assertTrue("Incorrect Number Of Root Directories.",
1711                     roots.length > 0);
1712         }
1713     }
1714 
1715     /**
1716      * java.io.File#mkdir()
1717      */
test_mkdir()1718     public void test_mkdir() throws IOException {
1719         String base = tempDirectory.getPath();
1720         // Old test left behind "garbage files" so this time it creates a
1721         // directory that is guaranteed not to already exist (and deletes it
1722         // afterward.)
1723         int dirNumber = 1;
1724         boolean dirExists = true;
1725         File dir = new File(base, String.valueOf(dirNumber));
1726         while (dirExists) {
1727             if (dir.exists()) {
1728                 dirNumber++;
1729                 dir = new File(base, String.valueOf(dirNumber));
1730             } else {
1731                 dirExists = false;
1732             }
1733         }
1734 
1735         assertTrue("mkdir failed", dir.mkdir());
1736         assertTrue("mkdir worked but exists check failed", dir.exists());
1737         dir.deleteOnExit();
1738 
1739         String longDirName = "abcdefghijklmnopqrstuvwx";// 24 chars
1740         String newbase = new String(dir + File.separator);
1741         StringBuilder sb = new StringBuilder(dir + File.separator);
1742         StringBuilder sb2 = new StringBuilder(dir + File.separator);
1743 
1744         // Test make a long path
1745         while (dir.getCanonicalPath().length() < 256 - longDirName.length()) {
1746             sb.append(longDirName + File.separator);
1747             dir = new File(sb.toString());
1748             assertTrue("mkdir failed", dir.mkdir());
1749             assertTrue("mkdir worked but exists check failed", dir.exists());
1750             dir.deleteOnExit();
1751         }
1752 
1753         while (dir.getCanonicalPath().length() < 256) {
1754             sb.append(0);
1755             dir = new File(sb.toString());
1756             assertTrue("mkdir " + dir.getCanonicalPath().length() + " failed",
1757                     dir.mkdir());
1758             assertTrue("mkdir " + dir.getCanonicalPath().length()
1759                     + " worked but exists check failed", dir.exists());
1760             dir.deleteOnExit();
1761         }
1762         dir = new File(sb2.toString());
1763         // Test make many paths
1764         while (dir.getCanonicalPath().length() < 256) {
1765             sb2.append(0);
1766             dir = new File(sb2.toString());
1767             assertTrue("mkdir " + dir.getCanonicalPath().length() + " failed",
1768                     dir.mkdir());
1769             assertTrue("mkdir " + dir.getCanonicalPath().length()
1770                     + " worked but exists check failed", dir.exists());
1771             dir.deleteOnExit();
1772         }
1773 
1774         // Regression test for HARMONY-3656
1775         String[] ss = { "dir\u3400", "abc", "abc@123", "!@#$%^&",
1776                 "~\u4E00!\u4E8C@\u4E09$", "\u56DB\u4E94\u516D",
1777                 "\u4E03\u516B\u4E5D" };
1778         for (int i = 0; i < ss.length; i++) {
1779             dir = new File(newbase, ss[i]);
1780             assertTrue("mkdir " + dir.getCanonicalPath() + " failed",
1781                     dir.mkdir());
1782             assertTrue("mkdir " + dir.getCanonicalPath()
1783                     + " worked but exists check failed",
1784                     dir.exists());
1785             dir.deleteOnExit();
1786         }
1787     }
1788 
1789     /**
1790      * java.io.File#mkdir()
1791      * <p/>
1792      * HARMONY-6041
1793      */
test_mkdir_special_unicode()1794     public void test_mkdir_special_unicode() throws IOException {
1795         File specialDir = new File(this.tempDirectory, "\u5C73");
1796         int i = 0;
1797         while (specialDir.exists()) {
1798             specialDir = new File("\u5C73" + i);
1799             ++i;
1800         }
1801         assertFalse(specialDir.exists());
1802         assertTrue(specialDir.mkdir());
1803         assertTrue(specialDir.exists());
1804     }
1805 
1806     /**
1807      * java.io.File#mkdirs()
1808      */
test_mkdirs()1809     public void test_mkdirs() {
1810         String userHome = addTrailingSlash(tempDirectory.getPath());
1811         File f = new File(userHome + "mdtest" + platformId + File.separator + "mdtest2",
1812                 "p.tst");
1813         File g = new File(userHome + "mdtest" + platformId + File.separator + "mdtest2");
1814         File h = new File(userHome + "mdtest" + platformId);
1815         f.mkdirs();
1816         try {
1817             assertTrue("Base Directory not created", h.exists());
1818             assertTrue("Directories not created", g.exists());
1819             assertTrue("File not created", f.exists());
1820         } finally {
1821             f.delete();
1822             g.delete();
1823             h.delete();
1824         }
1825     }
1826 
1827     /**
1828      * java.io.File#renameTo(java.io.File)
1829      */
test_renameToLjava_io_File()1830     public void test_renameToLjava_io_File() throws IOException {
1831         String base = tempDirectory.getPath();
1832         File dir = new File(base, platformId);
1833         dir.mkdir();
1834         File f = new File(dir, "xxx.xxx");
1835         File rfile = new File(dir, "yyy.yyy");
1836         File f2 = new File(dir, "zzz.zzz");
1837         try {
1838             FileOutputStream fos = new FileOutputStream(f);
1839             fos.write(fileString.getBytes());
1840             fos.close();
1841             long lengthOfFile = f.length();
1842 
1843             rfile.delete(); // in case it already exists
1844 
1845             assertTrue("Test 1: File Rename Failed", f.renameTo(rfile));
1846             assertTrue("Test 2: File Rename Failed.", rfile.exists());
1847             assertEquals("Test 3: Size Of File Changed.",
1848                     lengthOfFile, rfile.length());
1849 
1850             fos = new FileOutputStream(rfile);
1851             fos.close();
1852 
1853             f2.delete(); // in case it already exists
1854             assertTrue("Test 4: File Rename Failed", rfile.renameTo(f2));
1855             assertTrue("Test 5: File Rename Failed.", f2.exists());
1856         } finally {
1857             f.delete();
1858             rfile.delete();
1859             f2.delete();
1860             dir.delete();
1861         }
1862     }
1863 
1864     /**
1865      * java.io.File#setLastModified(long)
1866      */
test_setLastModifiedJ()1867     public void test_setLastModifiedJ() throws IOException {
1868         File f1 = null;
1869         try {
1870             f1 = File.createTempFile("harmony-test-FileTest_setLastModified", ".tmp");
1871             long orgTime = f1.lastModified();
1872             // Subtracting 100 000 milliseconds from the orgTime of File f1
1873             f1.setLastModified(orgTime - 100000);
1874             long lastModified = f1.lastModified();
1875             assertEquals("Test 1: LastModifed time incorrect",
1876                     orgTime - 100000, lastModified);
1877             // Subtracting 10 000 000 milliseconds from the orgTime of File f1
1878             f1.setLastModified(orgTime - 10000000);
1879             lastModified = f1.lastModified();
1880             assertEquals("Test 2: LastModifed time incorrect",
1881                     orgTime - 10000000, lastModified);
1882             // Adding 100 000 milliseconds to the orgTime of File f1
1883             f1.setLastModified(orgTime + 100000);
1884             lastModified = f1.lastModified();
1885             assertEquals("Test 3: LastModifed time incorrect",
1886                     orgTime + 100000, lastModified);
1887             // Adding 10 000 000 milliseconds from the orgTime of File f1
1888             f1.setLastModified(orgTime + 10000000);
1889             lastModified = f1.lastModified();
1890             assertEquals("Test 4: LastModifed time incorrect",
1891                     orgTime + 10000000, lastModified);
1892             // Trying to set time to an exact number
1893             f1.setLastModified(315550800000L);
1894             lastModified = f1.lastModified();
1895             assertEquals("Test 5: LastModified time incorrect",
1896                     315550800000L, lastModified);
1897             String osName = System.getProperty("os.name", "unknown");
1898             if (osName.equals("Windows 2000") || osName.equals("Windows NT")) {
1899                 // Trying to set time to a large exact number
1900                 boolean result = f1.setLastModified(4354837199000L);
1901                 long next = f1.lastModified();
1902                 // Dec 31 23:59:59 EST 2107 is overflow on FAT file systems, and
1903                 // the call fails
1904                 if (result) {
1905                     assertEquals("Test 6: LastModified time incorrect",
1906                             4354837199000L, next);
1907                 }
1908             }
1909             // Trying to set time to a negative number
1910             try {
1911                 f1.setLastModified(-25);
1912                 fail("IllegalArgumentException Not Thrown.");
1913             } catch (IllegalArgumentException e) {
1914             }
1915         } finally {
1916             if (f1 != null) {
1917                 f1.delete();
1918             }
1919         }
1920     }
1921 
1922     /**
1923      * java.io.File#setReadOnly()
1924      */
test_setReadOnly()1925     public void test_setReadOnly() throws Exception {
1926         File f1 = null;
1927         File f2 = null;
1928         if (Libcore.os.getuid() == 0) {
1929             System.err.println("Skipping #test_setReadOnly: test runner is root");
1930             return;
1931         }
1932 
1933         try {
1934             f1 = File.createTempFile("harmony-test-FileTest_setReadOnly", ".tmp");
1935             f2 = File.createTempFile("harmony-test-FileTest_setReadOnly", ".tmp");
1936             // Assert is flawed because canWrite does not work.
1937             // assertTrue("File f1 Is Set To ReadOnly." , f1.canWrite());
1938             assertTrue(f1.setReadOnly());
1939             assertFalse(f1.canWrite());
1940             // Assert is flawed because canWrite does not work.
1941             // assertTrue("File f1 Is Not Set To ReadOnly." , !f1.canWrite());
1942             try {
1943                 // Attempt to write to a file that is setReadOnly.
1944                 new FileOutputStream(f1);
1945                 fail("IOException not thrown.");
1946             } catch (IOException e) {
1947                 // Expected
1948             }
1949 
1950             Libcore.os.chmod(f1.getAbsolutePath(), 666);
1951 
1952             // Assert is flawed because canWrite does not work.
1953             // assertTrue("File f1 Is Set To ReadOnly." , f1.canWrite());
1954             FileOutputStream fos = new FileOutputStream(f1);
1955             fos.write(fileString.getBytes());
1956             fos.close();
1957             assertEquals(fileString.length(), f1.length());
1958             assertTrue(f1.delete());
1959 
1960             // Assert is flawed because canWrite does not work.
1961             // assertTrue("File f2 Is Set To ReadOnly." , f2.canWrite());
1962             fos = new FileOutputStream(f2);
1963             // Write to a file.
1964             fos.write(fileString.getBytes());
1965             fos.close();
1966             f2.setReadOnly();
1967             // Assert is flawed because canWrite does not work.
1968             // assertTrue("File f2 Is Not Set To ReadOnly." , !f2.canWrite());
1969             try {
1970                 // Attempt to write to a file that has previously been written
1971                 // to.
1972                 // and is now set to read only.
1973                 fos = new FileOutputStream(f2);
1974                 fail("IOException not thrown.");
1975             } catch (IOException e) {
1976                 // Expected
1977             }
1978 
1979             Libcore.os.chmod(f2.getAbsolutePath(), 666);
1980             assertTrue(f2.canWrite());
1981             fos = new FileOutputStream(f2);
1982             fos.write(fileString.getBytes());
1983             fos.close();
1984             f2.setReadOnly();
1985             assertTrue(f2.delete());
1986 
1987             // Similarly, trying to delete a read-only directory should succeed
1988             f2 = new File(tempDirectory, "deltestdir");
1989             f2.mkdir();
1990             f2.setReadOnly();
1991             assertTrue("Directory f2 Did Not Delete", f2.delete());
1992             assertTrue("Directory f2 Did Not Delete", !f2.exists());
1993         } finally {
1994             if (f1 != null) {
1995                 f1.delete();
1996             }
1997             if (f2 != null) {
1998                 f2.delete();
1999             }
2000         }
2001     }
2002 
2003     /**
2004      * java.io.File#toString()
2005      */
test_toString()2006     public void test_toString() {
2007         String fileName = System.getProperty("user.home");
2008         if (!fileName.endsWith(File.separator)) {
2009             fileName += File.separator;
2010         }
2011         fileName += "input.tst";
2012         File f = new File(fileName);
2013         assertEquals("Incorrect string returned", fileName, f.toString());
2014 
2015         if (File.separatorChar == '\\') {
2016             String result = new File("c:\\").toString();
2017             assertEquals("Removed backslash", "c:\\", result);
2018         }
2019     }
2020 
2021     /**
2022      * java.io.File#toURI()
2023      */
test_toURI()2024     public void test_toURI() throws URISyntaxException {
2025         // Need a directory that exists
2026         File dir = tempDirectory;
2027 
2028         // Test for toURI when the file is a directory.
2029         String newURIPath = dir.getAbsolutePath();
2030         newURIPath = newURIPath.replace(File.separatorChar, '/');
2031         if (!newURIPath.startsWith("/")) {
2032             newURIPath = "/" + newURIPath;
2033         }
2034         if (!newURIPath.endsWith("/")) {
2035             newURIPath += '/';
2036         }
2037 
2038         URI uri = dir.toURI();
2039         assertEquals("Test 1A: Incorrect URI Returned.", dir.getAbsoluteFile(), new File(uri));
2040         assertEquals("Test 1B: Incorrect URI Returned.",
2041                 new URI("file", null, newURIPath, null, null), uri);
2042 
2043         // Test for toURI with a file name with illegal chars.
2044         File f = new File(dir, "te% \u20ac st.tst");
2045         newURIPath = f.getAbsolutePath();
2046         newURIPath = newURIPath.replace(File.separatorChar, '/');
2047         if (!newURIPath.startsWith("/")) {
2048             newURIPath = "/" + newURIPath;
2049         }
2050 
2051         uri = f.toURI();
2052         assertEquals("Test 2A: Incorrect URI Returned.",
2053                 f.getAbsoluteFile(), new File(uri));
2054         assertEquals("Test 2B: Incorrect URI Returned.",
2055                 new URI("file", null, newURIPath, null, null), uri);
2056 
2057         // Regression test for HARMONY-3207
2058         dir = new File(""); // current directory
2059         uri = dir.toURI();
2060         assertTrue("Test current dir: URI does not end with slash.", uri
2061                 .toString().endsWith("/"));
2062     }
2063 
2064     /**
2065      * java.io.File#toURL()
2066      */
test_toURL()2067     public void test_toURL() throws MalformedURLException {
2068         // Need a directory that exists
2069         File dir = tempDirectory;
2070 
2071         // Test for toURL when the file is a directory.
2072         String newDirURL = dir.getAbsolutePath();
2073         newDirURL = newDirURL.replace(File.separatorChar, '/');
2074         if (newDirURL.startsWith("/")) {
2075             newDirURL = "file://" + newDirURL;
2076         } else {
2077             newDirURL = "file:///" + newDirURL;
2078         }
2079         if (!newDirURL.endsWith("/")) {
2080             newDirURL += '/';
2081         }
2082         assertEquals("Test 1: Incorrect URL Returned.",
2083                 dir.toURL().toString(), newDirURL);
2084 
2085         // Test for toURL with a file.
2086         File f = new File(dir, "test.tst");
2087         String newURL = f.getAbsolutePath();
2088         newURL = newURL.replace(File.separatorChar, '/');
2089         if (newURL.startsWith("/")) {
2090             newURL = "file://" + newURL;
2091         } else {
2092             newURL = "file:///" + newURL;
2093         }
2094         assertEquals("Test 2: Incorrect URL Returned.",
2095                 f.toURL().toString(), newURL);
2096 
2097         // Regression test for HARMONY-3207
2098         dir = new File(""); // current directory
2099         newDirURL = dir.toURL().toString();
2100         assertTrue("Test current dir: URL does not end with slash.", newDirURL
2101                 .endsWith("/"));
2102     }
2103 
2104     /**
2105      * java.io.File#toURI()
2106      */
test_toURI2()2107     public void test_toURI2() throws URISyntaxException {
2108         File f = new File(tempDirectory, "a/b/c/../d/e/./f");
2109 
2110         String path = f.getAbsolutePath();
2111         path = path.replace(File.separatorChar, '/');
2112         if (!path.startsWith("/")) {
2113             path = "/" + path;
2114         }
2115 
2116         URI uri1 = new URI("file", null, path, null);
2117         URI uri2 = f.toURI();
2118         assertEquals("uris not equal", uri1, uri2);
2119     }
2120 
2121     /**
2122      * java.io.File#toURL()
2123      */
test_toURL2()2124     public void test_toURL2() throws MalformedURLException {
2125         File f = new File(tempDirectory, "a/b/c/../d/e/./f");
2126 
2127         String path = f.getAbsolutePath();
2128         path = path.replace(File.separatorChar, '/');
2129         if (!path.startsWith("/")) {
2130             path = "/" + path;
2131         }
2132 
2133         URL url1 = new URL("file", "", path);
2134         URL url2 = f.toURL();
2135         assertEquals("urls not equal", url1, url2);
2136     }
2137 
2138     /**
2139      * serialization
2140      */
test_objectStreamClass_getFields()2141     public void test_objectStreamClass_getFields() throws Exception {
2142         // Regression for HARMONY-2674
2143         ObjectStreamClass objectStreamClass = ObjectStreamClass
2144                 .lookup(File.class);
2145         ObjectStreamField[] objectStreamFields = objectStreamClass.getFields();
2146         assertEquals(1, objectStreamFields.length);
2147         ObjectStreamField objectStreamField = objectStreamFields[0];
2148         assertEquals("path", objectStreamField.getName());
2149         assertEquals(String.class, objectStreamField.getType());
2150     }
2151 
2152     // Regression test for HARMONY-4493
test_list_withUnicodeFileName()2153     public void test_list_withUnicodeFileName() throws Exception {
2154         File rootDir = new File(System.getProperty("java.io.tmpdir")).getAbsoluteFile();
2155         String dirName = new String("src\u3400");
2156         File dir = new File(rootDir, dirName);
2157         if (!dir.exists()) {
2158             dir.mkdir();
2159             dir.deleteOnExit();
2160         }
2161         boolean exist = false;
2162         String[] fileNames = rootDir.list();
2163         for (String fileName : fileNames) {
2164             if (dirName.equals(fileName)) {
2165                 exist = true;
2166                 break;
2167             }
2168         }
2169         assertTrue(exist);
2170     }
2171 
2172     /**
2173      * serialization/deserialization.
2174      */
test_serialization_self()2175     public void test_serialization_self() throws Exception {
2176         File testFile = new File("test.ser");
2177         SerializationTest.verifySelf(testFile);
2178     }
2179 
2180     /**
2181      * serialization/deserialization compatibility with RI.
2182      */
test_serialization_compatibility()2183     public void test_serialization_compatibility() throws Exception {
2184         File file = new File("FileTest.golden.ser");
2185         SerializationTest.verifyGolden(this, file);
2186     }
2187 }
2188