PageRenderTime 67ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/luni/src/test/java/tests/api/java/io/FileTest.java

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