0001: /*
0002: * Licensed to the Apache Software Foundation (ASF) under one or more
0003: * contributor license agreements. See the NOTICE file distributed with
0004: * this work for additional information regarding copyright ownership.
0005: * The ASF licenses this file to You under the Apache License, Version 2.0
0006: * (the "License"); you may not use this file except in compliance with
0007: * the License. You may obtain a copy of the License at
0008: *
0009: * http://www.apache.org/licenses/LICENSE-2.0
0010: *
0011: * Unless required by applicable law or agreed to in writing, software
0012: * distributed under the License is distributed on an "AS IS" BASIS,
0013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014: * See the License for the specific language governing permissions and
0015: * limitations under the License.
0016: */
0017:
0018: package org.apache.harmony.luni.tests.java.io;
0019:
0020: import java.io.File;
0021: import java.io.FileFilter;
0022: import java.io.FileInputStream;
0023: import java.io.FileOutputStream;
0024: import java.io.FilenameFilter;
0025: import java.io.IOException;
0026: import java.io.ObjectStreamClass;
0027: import java.io.ObjectStreamField;
0028: import java.io.RandomAccessFile;
0029: import java.net.MalformedURLException;
0030: import java.net.URI;
0031: import java.net.URISyntaxException;
0032: import java.net.URL;
0033:
0034: import junit.framework.TestCase;
0035:
0036: import org.apache.harmony.testframework.serialization.SerializationTest;
0037:
0038: import tests.support.Support_Exec;
0039: import tests.support.Support_PlatformFile;
0040:
0041: public class FileTest extends TestCase {
0042:
0043: /** Location to store tests in */
0044: private File tempDirectory;
0045:
0046: /** Temp file that does exist */
0047: private File tempFile;
0048:
0049: /** File separator */
0050: private String slash = File.separator;
0051:
0052: 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";
0053:
0054: private static String platformId = "JDK"
0055: + System.getProperty("java.vm.version").replace('.', '-');
0056:
0057: {
0058: // Delete all old temporary files
0059: File tempDir = new File(System.getProperty("java.io.tmpdir"));
0060: String[] files = tempDir.list();
0061: for (int i = 0; i < files.length; i++) {
0062: File f = new File(tempDir, files[i]);
0063: if (f.isDirectory()) {
0064: if (files[i].startsWith("hyts_resources")) {
0065: deleteTempFolder(f);
0066: }
0067: }
0068: if (files[i].startsWith("hyts_")
0069: || files[i].startsWith("hyjar_")) {
0070: new File(tempDir, files[i]).delete();
0071: }
0072: }
0073: }
0074:
0075: private void deleteTempFolder(File dir) {
0076: String files[] = dir.list();
0077: for (int i = 0; i < files.length; i++) {
0078: File f = new File(dir, files[i]);
0079: if (f.isDirectory()) {
0080: deleteTempFolder(f);
0081: } else {
0082: f.delete();
0083: }
0084: }
0085: dir.delete();
0086: }
0087:
0088: /**
0089: * @tests java.io.File#File(java.io.File, java.lang.String)
0090: */
0091: public void test_ConstructorLjava_io_FileLjava_lang_String() {
0092: String dirName = System.getProperty("user.dir");
0093: File d = new File(dirName);
0094: File f = new File(d, "input.tst");
0095: if (!dirName.regionMatches((dirName.length() - 1), slash, 0, 1)) {
0096: dirName += slash;
0097: }
0098: dirName += "input.tst";
0099: assertEquals("Test 1: Created Incorrect File ", dirName, f
0100: .getPath());
0101:
0102: String fileName = null;
0103: try {
0104: f = new File(d, fileName);
0105: fail("NullPointerException Not Thrown.");
0106: } catch (NullPointerException e) {
0107: }
0108:
0109: d = null;
0110: f = new File(d, "input.tst");
0111: assertEquals("Test 2: Created Incorrect File", dirName, f
0112: .getAbsolutePath());
0113:
0114: // Regression test for HARMONY-382
0115: File s = null;
0116: f = new File("/abc");
0117: d = new File(s, "/abc");
0118: assertEquals("Test3: Created Incorrect File", d
0119: .getAbsolutePath(), f.getAbsolutePath());
0120:
0121: // Regression test for HARMONY-21
0122: File path = new File("/dir/file");
0123: File root = new File("/");
0124: File file = new File(root, "/dir/file");
0125: assertEquals("Assert 1: wrong path result ", path.getPath(),
0126: file.getPath());
0127: assertTrue("Assert 1.1: path not absolute ", new File(
0128: "\\\\\\a\b").isAbsolute());
0129:
0130: // Test data used in a few places below
0131: dirName = System.getProperty("user.dir");
0132: fileName = "input.tst";
0133:
0134: // Check filename is preserved correctly
0135: d = new File(dirName);
0136: f = new File(d, fileName);
0137: if (!dirName.regionMatches((dirName.length() - 1),
0138: File.separator, 0, 1)) {
0139: dirName += File.separator;
0140: }
0141: dirName += fileName;
0142: assertEquals("Assert 2: Created incorrect file ", dirName, f
0143: .getPath());
0144:
0145: // Check null argument is handled
0146: try {
0147: f = new File(d, null);
0148: fail("Assert 3: NullPointerException not thrown.");
0149: } catch (NullPointerException e) {
0150: // Expected.
0151: }
0152:
0153: f = new File((File) null, fileName);
0154: assertTrue("Assert 4: Created incorrect file " + f.getPath(), f
0155: .getAbsolutePath().equals(dirName));
0156:
0157: // Regression for HARMONY-46
0158: File f1 = new File("a");
0159: File f2 = new File("a/");
0160: assertEquals("Assert 5: Trailing slash file name is incorrect",
0161: f1, f2);
0162: }
0163:
0164: /**
0165: * @tests java.io.File#File(java.lang.String)
0166: */
0167: public void test_ConstructorLjava_lang_String() {
0168: String fileName = null;
0169: try {
0170: new File(fileName);
0171: fail("NullPointerException Not Thrown.");
0172: } catch (NullPointerException e) {
0173: // Expected
0174: }
0175:
0176: fileName = System.getProperty("user.dir");
0177: if (!fileName.regionMatches((fileName.length() - 1), slash, 0,
0178: 1)) {
0179: fileName += slash;
0180: }
0181: fileName += "input.tst";
0182:
0183: File f = new File(fileName);
0184: assertEquals("Created incorrect File", fileName, f.getPath());
0185: }
0186:
0187: /**
0188: * @tests java.io.File#File(java.lang.String, java.lang.String)
0189: */
0190: public void test_ConstructorLjava_lang_StringLjava_lang_String() {
0191: String dirName = null;
0192: String fileName = "input.tst";
0193: File f = new File(dirName, fileName);
0194: String userDir = System.getProperty("user.dir");
0195: if (!userDir.regionMatches((userDir.length() - 1), slash, 0, 1)) {
0196: userDir += slash;
0197: }
0198: userDir += "input.tst";
0199: assertEquals("Test 1: Created Incorrect File.", userDir, f
0200: .getAbsolutePath());
0201:
0202: dirName = System.getProperty("user.dir");
0203: fileName = null;
0204: try {
0205: f = new File(dirName, fileName);
0206: fail("NullPointerException Not Thrown.");
0207: } catch (NullPointerException e) {
0208: // Expected
0209: }
0210:
0211: fileName = "input.tst";
0212: f = new File(dirName, fileName);
0213: assertEquals("Test 2: Created Incorrect File", userDir, f
0214: .getPath());
0215:
0216: // Regression test for HARMONY-382
0217: String s = null;
0218: f = new File("/abc");
0219: File d = new File(s, "/abc");
0220: assertEquals("Test3: Created Incorrect File", d
0221: .getAbsolutePath(), f.getAbsolutePath());
0222: }
0223:
0224: /**
0225: * @tests java.io.File#File(java.lang.String, java.lang.String)
0226: */
0227: public void test_Constructor_String_String_112270() {
0228: File ref1 = new File("/dir1/file1");
0229:
0230: File file1 = new File("/", "/dir1/file1");
0231: assertEquals("wrong result 1", ref1.getPath(), file1.getPath());
0232: File file2 = new File("/", "//dir1/file1");
0233: assertEquals("wrong result 2", ref1.getPath(), file2.getPath());
0234: File file3 = new File("\\", "\\dir1\\file1");
0235: assertEquals("wrong result 3", ref1.getPath(), file3.getPath());
0236: File file4 = new File("\\", "\\\\dir1\\file1");
0237: assertEquals("wrong result 4", ref1.getPath(), file4.getPath());
0238:
0239: File ref2 = new File("/lib/content-types.properties");
0240: File file5 = new File("/", "lib/content-types.properties");
0241: assertEquals("wrong result 5", ref2.getPath(), file5.getPath());
0242: }
0243:
0244: /**
0245: * @tests java.io.File#File(java.io.File, java.lang.String)
0246: */
0247: public void test_Constructor_File_String_112270() {
0248: File ref1 = new File("/dir1/file1");
0249:
0250: File root = new File("/");
0251: File file1 = new File(root, "/dir1/file1");
0252: assertEquals("wrong result 1", ref1.getPath(), file1.getPath());
0253: File file2 = new File(root, "//dir1/file1");
0254: assertEquals("wrong result 2", ref1.getPath(), file2.getPath());
0255: File file3 = new File(root, "\\dir1\\file1");
0256: assertEquals("wrong result 3", ref1.getPath(), file3.getPath());
0257: File file4 = new File(root, "\\\\dir1\\file1");
0258: assertEquals("wrong result 4", ref1.getPath(), file4.getPath());
0259:
0260: File ref2 = new File("/lib/content-types.properties");
0261: File file5 = new File(root, "lib/content-types.properties");
0262: assertEquals("wrong result 5", ref2.getPath(), file5.getPath());
0263: }
0264:
0265: /**
0266: * @tests java.io.File#File(java.net.URI)
0267: */
0268: public void test_ConstructorLjava_net_URI()
0269: throws URISyntaxException {
0270: URI uri = null;
0271: try {
0272: new File(uri);
0273: fail("NullPointerException Not Thrown.");
0274: } catch (NullPointerException e) {
0275: // Expected
0276: }
0277:
0278: // invalid file URIs
0279: String[] uris = new String[] { "mailto:user@domain.com", // not
0280: // hierarchical
0281: "ftp:///path", // not file scheme
0282: "//host/path/", // not absolute
0283: "file://host/path", // non empty authority
0284: "file:///path?query", // non empty query
0285: "file:///path#fragment", // non empty fragment
0286: "file:///path?", "file:///path#" };
0287:
0288: for (int i = 0; i < uris.length; i++) {
0289: uri = new URI(uris[i]);
0290: try {
0291: new File(uri);
0292: fail("Expected IllegalArgumentException for new File("
0293: + uri + ")");
0294: } catch (IllegalArgumentException e) {
0295: // Expected
0296: }
0297: }
0298:
0299: // a valid File URI
0300: File f = new File(new URI(
0301: "file:///pa%20th/another\u20ac/pa%25th"));
0302: assertTrue("Created incorrect File " + f.getPath(), f.getPath()
0303: .equals(
0304: slash + "pa th" + slash + "another\u20ac"
0305: + slash + "pa%th"));
0306: }
0307:
0308: /**
0309: * @tests java.io.File#canRead()
0310: */
0311: public void test_canRead() throws IOException {
0312: // canRead only returns if the file exists so cannot be fully tested.
0313: File f = new File(System.getProperty("java.io.tmpdir"),
0314: platformId + "canRead.tst");
0315: try {
0316: FileOutputStream fos = new FileOutputStream(f);
0317: fos.close();
0318: assertTrue("canRead returned false", f.canRead());
0319: f.delete();
0320: } finally {
0321: f.delete();
0322: }
0323: }
0324:
0325: /**
0326: * @tests java.io.File#canWrite()
0327: */
0328: public void test_canWrite() throws IOException {
0329: // canWrite only returns if the file exists so cannot be fully tested.
0330: File f = new File(System.getProperty("java.io.tmpdir"),
0331: platformId + "canWrite.tst");
0332: try {
0333: FileOutputStream fos = new FileOutputStream(f);
0334: fos.close();
0335: assertTrue("canWrite returned false", f.canWrite());
0336: } finally {
0337: f.delete();
0338: }
0339: }
0340:
0341: /**
0342: * @tests java.io.File#compareTo(java.io.File)
0343: */
0344: public void test_compareToLjava_io_File() {
0345: File f1 = new File("thisFile.file");
0346: File f2 = new File("thisFile.file");
0347: File f3 = new File("thatFile.file");
0348: assertEquals("Equal files did not answer zero for compareTo",
0349: 0, f1.compareTo(f2));
0350: assertTrue("f3.compareTo(f1) did not result in value < 0", f3
0351: .compareTo(f1) < 0);
0352: assertTrue("f1.compareTo(f3) did not result in value > 0", f1
0353: .compareTo(f3) > 0);
0354: }
0355:
0356: /**
0357: * @tests java.io.File#createNewFile()
0358: */
0359: public void test_createNewFile_EmptyString() {
0360: File f = new File("");
0361: try {
0362: f.createNewFile();
0363: fail("should throw IOException");
0364: } catch (IOException e) {
0365: // expected
0366: }
0367: }
0368:
0369: /**
0370: * @tests java.io.File#createNewFile()
0371: */
0372: public void test_createNewFile() throws IOException {
0373: String base = System.getProperty("java.io.tmpdir");
0374: boolean dirExists = true;
0375: int numDir = 1;
0376: File dir = new File(base, String.valueOf(numDir));
0377: // Making sure that the directory does not exist.
0378: while (dirExists) {
0379: // If the directory exists, add one to the directory number
0380: // (making it a new directory name.)
0381: if (dir.exists()) {
0382: numDir++;
0383: dir = new File(base, String.valueOf(numDir));
0384: } else {
0385: dirExists = false;
0386: }
0387: }
0388:
0389: // Test for trying to create a file in a directory that does not
0390: // exist.
0391: try {
0392: // Try to create a file in a directory that does not exist
0393: File f1 = new File(dir, "tempfile.tst");
0394: f1.createNewFile();
0395: fail("IOException not thrown");
0396: } catch (IOException e) {
0397: // Expected
0398: }
0399:
0400: dir.mkdir();
0401:
0402: File f1 = new File(dir, "tempfile.tst");
0403: File f2 = new File(dir, "tempfile.tst");
0404: f1.deleteOnExit();
0405: f2.deleteOnExit();
0406: dir.deleteOnExit();
0407: assertFalse("File Should Not Exist", f1.isFile());
0408: f1.createNewFile();
0409: assertTrue("File Should Exist.", f1.isFile());
0410: assertTrue("File Should Exist.", f2.isFile());
0411: String dirName = f1.getParent();
0412: if (!dirName.endsWith(slash)) {
0413: dirName += slash;
0414: }
0415: assertEquals("File Saved To Wrong Directory.", dir.getPath()
0416: + slash, dirName);
0417: assertEquals("File Saved With Incorrect Name.", "tempfile.tst",
0418: f1.getName());
0419:
0420: // Test for creating a file that already exists.
0421: assertFalse(
0422: "File Already Exists, createNewFile Should Return False.",
0423: f2.createNewFile());
0424:
0425: // Test create an illegal file
0426: String sep = File.separator;
0427: f1 = new File(sep + "..");
0428: try {
0429: f1.createNewFile();
0430: fail("should throw IOE");
0431: } catch (IOException e) {
0432: // expected;
0433: }
0434: f1 = new File(sep + "a" + sep + ".." + sep + ".." + sep);
0435: try {
0436: f1.createNewFile();
0437: fail("should throw IOE");
0438: } catch (IOException e) {
0439: // expected;
0440: }
0441:
0442: // This test is invalid. createNewFile should return false
0443: // not IOE when the file exists (in this case it exists and is
0444: // a directory). TODO: We should probably replace this test
0445: // with some that cover this behaviour. It might even be
0446: // different on unix and windows since it directly reflects
0447: // the open syscall behaviour.
0448: //
0449: // // Test create an exist path
0450: // f1 = new File(base);
0451: // try {
0452: // assertFalse(f1.createNewFile());
0453: // fail("should throw IOE");
0454: // } catch (IOException e) {
0455: // // expected;
0456: // }
0457: }
0458:
0459: /**
0460: * @tests java.io.File#createTempFile(java.lang.String, java.lang.String)
0461: */
0462: public void test_createTempFileLjava_lang_StringLjava_lang_String()
0463: throws IOException {
0464: // Error protection against using a suffix without a "."?
0465: File f1 = null;
0466: File f2 = null;
0467: try {
0468: f1 = File.createTempFile("hyts_abc", ".tmp");
0469: f2 = File.createTempFile("hyts_tf", null);
0470: String fileLocation = f1.getParent();
0471: if (!fileLocation.endsWith(slash)) {
0472: fileLocation += slash;
0473: }
0474: String tempDir = System.getProperty("java.io.tmpdir");
0475: if (!tempDir.endsWith(slash)) {
0476: tempDir += slash;
0477: }
0478: assertEquals(
0479: "File did not save to the default temporary-file location.",
0480: tempDir, fileLocation);
0481:
0482: // Test to see if correct suffix was used to create the tempfile.
0483: File currentFile;
0484: String fileName;
0485: // Testing two files, one with suffix ".tmp" and one with null
0486: for (int i = 0; i < 2; i++) {
0487: currentFile = i == 0 ? f1 : f2;
0488: fileName = currentFile.getPath();
0489: assertTrue("File Created With Incorrect Suffix.",
0490: fileName.endsWith(".tmp"));
0491: }
0492:
0493: // Tests to see if the correct prefix was used to create the
0494: // tempfiles.
0495: fileName = f1.getName();
0496: assertTrue("Test 1: File Created With Incorrect Prefix.",
0497: fileName.startsWith("hyts_abc"));
0498: fileName = f2.getName();
0499: assertTrue("Test 2: File Created With Incorrect Prefix.",
0500: fileName.startsWith("hyts_tf"));
0501:
0502: // Tests for creating a tempfile with a filename shorter than 3
0503: // characters.
0504: try {
0505: File f3 = File.createTempFile("ab", ".tst");
0506: f3.delete();
0507: fail("IllegalArgumentException Not Thrown.");
0508: } catch (IllegalArgumentException e) {
0509: // Expected
0510: }
0511: try {
0512: File f3 = File.createTempFile("a", ".tst");
0513: f3.delete();
0514: fail("IllegalArgumentException Not Thrown.");
0515: } catch (IllegalArgumentException e) {
0516: // Expected
0517: }
0518: try {
0519: File f3 = File.createTempFile("", ".tst");
0520: f3.delete();
0521: fail("IllegalArgumentException Not Thrown.");
0522: } catch (IllegalArgumentException e) {
0523: // Expected
0524: }
0525: } finally {
0526: if (f1 != null) {
0527: f1.delete();
0528: }
0529: if (f2 != null) {
0530: f2.delete();
0531: }
0532: }
0533: }
0534:
0535: /**
0536: * @tests java.io.File#createTempFile(java.lang.String, java.lang.String,
0537: * java.io.File)
0538: */
0539: public void test_createTempFileLjava_lang_StringLjava_lang_StringLjava_io_File()
0540: throws IOException {
0541: File f1 = null;
0542: File f2 = null;
0543: String base = System.getProperty("java.io.tmpdir");
0544: try {
0545: // Test to make sure that the tempfile was saved in the correct
0546: // location and with the correct prefix/suffix.
0547: f1 = File.createTempFile("hyts_tf", null, null);
0548: File dir = new File(base);
0549: f2 = File.createTempFile("hyts_tf", ".tmp", dir);
0550: File currentFile;
0551: String fileLocation;
0552: String fileName;
0553: for (int i = 0; i < 2; i++) {
0554: currentFile = i == 0 ? f1 : f2;
0555: fileLocation = currentFile.getParent();
0556: if (!fileLocation.endsWith(slash)) {
0557: fileLocation += slash;
0558: }
0559: if (!base.endsWith(slash)) {
0560: base += slash;
0561: }
0562: assertEquals(
0563: "File not created in the default temporary-file location.",
0564: base, fileLocation);
0565: fileName = currentFile.getName();
0566: assertTrue("File created with incorrect suffix.",
0567: fileName.endsWith(".tmp"));
0568: assertTrue("File created with incorrect prefix.",
0569: fileName.startsWith("hyts_tf"));
0570: currentFile.delete();
0571: }
0572:
0573: // Test for creating a tempfile in a directory that does not exist.
0574: int dirNumber = 1;
0575: boolean dirExists = true;
0576: // Set dir to a non-existent directory inside the temporary
0577: // directory
0578: dir = new File(base, String.valueOf(dirNumber));
0579: // Making sure that the directory does not exist.
0580: while (dirExists) {
0581: // If the directory exists, add one to the directory number
0582: // (making it
0583: // a new directory name.)
0584: if (dir.exists()) {
0585: dirNumber++;
0586: dir = new File(base, String.valueOf(dirNumber));
0587: } else {
0588: dirExists = false;
0589: }
0590: }
0591: try {
0592: // Try to create a file in a directory that does not exist
0593: File f3 = File.createTempFile("hyts_tf", null, dir);
0594: f3.delete();
0595: fail("IOException not thrown");
0596: } catch (IOException e) {
0597: // Expected
0598: }
0599: dir.delete();
0600:
0601: // Tests for creating a tempfile with a filename shorter than 3
0602: // characters.
0603: try {
0604: File f4 = File.createTempFile("ab", null, null);
0605: f4.delete();
0606: fail("IllegalArgumentException not thrown.");
0607: } catch (IllegalArgumentException e) {
0608: // Expected
0609: }
0610: try {
0611: File f4 = File.createTempFile("a", null, null);
0612: f4.delete();
0613: fail("IllegalArgumentException not thrown.");
0614: } catch (IllegalArgumentException e) {
0615: // Expected
0616: }
0617: try {
0618: File f4 = File.createTempFile("", null, null);
0619: f4.delete();
0620: fail("IllegalArgumentException not thrown.");
0621: } catch (IllegalArgumentException e) {
0622: // Expected
0623: }
0624: } finally {
0625: if (f1 != null) {
0626: f1.delete();
0627: }
0628: if (f2 != null) {
0629: f1.delete();
0630: }
0631: }
0632: }
0633:
0634: /**
0635: * @tests java.io.File#delete()
0636: */
0637: public void test_delete() throws IOException {
0638: File dir = new File(System.getProperty("user.dir"), platformId
0639: + "filechk");
0640: dir.mkdir();
0641: assertTrue("Directory does not exist", dir.exists());
0642: assertTrue("Directory is not directory", dir.isDirectory());
0643: File f = new File(dir, "filechk.tst");
0644: FileOutputStream fos = new FileOutputStream(f);
0645: fos.close();
0646: assertTrue("Error Creating File For Delete Test", f.exists());
0647: dir.delete();
0648: assertTrue("Directory Should Not Have Been Deleted.", dir
0649: .exists());
0650: f.delete();
0651: assertTrue("File Was Not Deleted", !f.exists());
0652: dir.delete();
0653: assertTrue("Directory Was Not Deleted", !dir.exists());
0654: }
0655:
0656: // GCH
0657: // TODO : This test passes on Windows but fails on Linux with a
0658: // java.lang.NoClassDefFoundError. Temporarily removing from the test
0659: // suite while I investigate the cause.
0660: // /**
0661: // * @tests java.io.File#deleteOnExit()
0662: // */
0663: // public void test_deleteOnExit() {
0664: // File f1 = new File(System.getProperty("java.io.tmpdir"), platformId
0665: // + "deleteOnExit.tst");
0666: // try {
0667: // FileOutputStream fos = new FileOutputStream(f1);
0668: // fos.close();
0669: // } catch (IOException e) {
0670: // fail("Unexpected IOException During Test : " + e.getMessage());
0671: // }
0672: // assertTrue("File Should Exist.", f1.exists());
0673: //
0674: // try {
0675: // Support_Exec.execJava(new String[] {
0676: // "tests.support.Support_DeleteOnExitTest", f1.getPath() },
0677: // null, true);
0678: // } catch (IOException e) {
0679: // fail("Unexpected IOException During Test + " + e.getMessage());
0680: // } catch (InterruptedException e) {
0681: // fail("Unexpected InterruptedException During Test: " + e);
0682: // }
0683: //
0684: // boolean gone = !f1.exists();
0685: // f1.delete();
0686: // assertTrue("File Should Already Be Deleted.", gone);
0687: // }
0688:
0689: /**
0690: * @tests java.io.File#equals(java.lang.Object)
0691: */
0692: public void test_equalsLjava_lang_Object() throws IOException {
0693: File f1 = new File("filechk.tst");
0694: File f2 = new File("filechk.tst");
0695: File f3 = new File("xxxx");
0696:
0697: assertTrue("Equality test failed", f1.equals(f2));
0698: assertTrue("Files Should Not Return Equal.", !f1.equals(f3));
0699:
0700: f3 = new File("FiLeChK.tst");
0701: boolean onWindows = File.separatorChar == '\\';
0702: boolean onUnix = File.separatorChar == '/';
0703: if (onWindows) {
0704: assertTrue("Files Should Return Equal.", f1.equals(f3));
0705: } else if (onUnix) {
0706: assertTrue("Files Should NOT Return Equal.", !f1.equals(f3));
0707: }
0708:
0709: f1 = new File(System.getProperty("java.io.tmpdir"),
0710: "casetest.tmp");
0711: f2 = new File(System.getProperty("java.io.tmpdir"),
0712: "CaseTest.tmp");
0713: new FileOutputStream(f1).close(); // create the file
0714: if (f1.equals(f2)) {
0715: try {
0716: new FileInputStream(f2);
0717: } catch (IOException e) {
0718: fail("File system is case sensitive");
0719: }
0720: } else {
0721: boolean exception = false;
0722: try {
0723: new FileInputStream(f2);
0724: } catch (IOException e) {
0725: exception = true;
0726: }
0727: assertTrue("File system is case insensitive", exception);
0728: }
0729: f1.delete();
0730: }
0731:
0732: /**
0733: * @tests java.io.File#exists()
0734: */
0735: public void test_exists() throws IOException {
0736: File f = new File(System.getProperty("user.dir"), platformId
0737: + "exists.tst");
0738: assertTrue("Exists returned true for non-existent file", !f
0739: .exists());
0740: FileOutputStream fos = new FileOutputStream(f);
0741: fos.close();
0742: assertTrue("Exists returned false file", f.exists());
0743: f.delete();
0744: }
0745:
0746: /**
0747: * @tests java.io.File#getAbsoluteFile()
0748: */
0749: public void test_getAbsoluteFile() {
0750: String base = System.getProperty("user.dir");
0751: if (!base.endsWith(slash)) {
0752: base += slash;
0753: }
0754: File f = new File(base, "temp.tst");
0755: File f2 = f.getAbsoluteFile();
0756: assertEquals("Test 1: Incorrect File Returned.", 0, f2
0757: .compareTo(f.getAbsoluteFile()));
0758: f = new File(base + "Temp" + slash + slash + "temp.tst");
0759: f2 = f.getAbsoluteFile();
0760: assertEquals("Test 2: Incorrect File Returned.", 0, f2
0761: .compareTo(f.getAbsoluteFile()));
0762: f = new File(base + slash + ".." + slash + "temp.tst");
0763: f2 = f.getAbsoluteFile();
0764: assertEquals("Test 3: Incorrect File Returned.", 0, f2
0765: .compareTo(f.getAbsoluteFile()));
0766: f.delete();
0767: f2.delete();
0768: }
0769:
0770: /**
0771: * @tests java.io.File#getAbsolutePath()
0772: */
0773: public void test_getAbsolutePath() {
0774: String base = System.getProperty("user.dir");
0775: if (!base.regionMatches((base.length() - 1), slash, 0, 1)) {
0776: base += slash;
0777: }
0778: File f = new File(base, "temp.tst");
0779: assertEquals("Test 1: Incorrect Path Returned.", base
0780: + "temp.tst", f.getAbsolutePath());
0781:
0782: f = new File(base + "Temp" + slash + slash + slash + "Testing"
0783: + slash + "temp.tst");
0784: assertEquals("Test 2: Incorrect Path Returned.", base + "Temp"
0785: + slash + "Testing" + slash + "temp.tst", f
0786: .getAbsolutePath());
0787:
0788: f = new File(base + "a" + slash + slash + ".." + slash
0789: + "temp.tst");
0790: assertEquals("Test 3: Incorrect Path Returned.", base + "a"
0791: + slash + ".." + slash + "temp.tst", f
0792: .getAbsolutePath());
0793: f.delete();
0794: }
0795:
0796: /**
0797: * @tests java.io.File#getCanonicalFile()
0798: */
0799: public void test_getCanonicalFile() throws IOException {
0800: String base = System.getProperty("user.dir");
0801: if (!base.endsWith(slash)) {
0802: base += slash;
0803: }
0804: File f = new File(base, "temp.tst");
0805: File f2 = f.getCanonicalFile();
0806: assertEquals("Test 1: Incorrect File Returned.", 0, f2
0807: .getCanonicalFile().compareTo(f.getCanonicalFile()));
0808: f = new File(base + "Temp" + slash + slash + "temp.tst");
0809: f2 = f.getCanonicalFile();
0810: assertEquals("Test 2: Incorrect File Returned.", 0, f2
0811: .getCanonicalFile().compareTo(f.getCanonicalFile()));
0812: f = new File(base + "Temp" + slash + slash + ".." + slash
0813: + "temp.tst");
0814: f2 = f.getCanonicalFile();
0815: assertEquals("Test 3: Incorrect File Returned.", 0, f2
0816: .getCanonicalFile().compareTo(f.getCanonicalFile()));
0817:
0818: // Test for when long directory/file names in Windows
0819: boolean onWindows = File.separatorChar == '\\';
0820: if (onWindows) {
0821: File testdir = new File(base, "long-" + platformId);
0822: testdir.mkdir();
0823: File dir = new File(testdir, "longdirectory" + platformId);
0824: try {
0825: dir.mkdir();
0826: f = new File(dir, "longfilename.tst");
0827: f2 = f.getCanonicalFile();
0828: assertEquals("Test 4: Incorrect File Returned.", 0, f2
0829: .getCanonicalFile().compareTo(
0830: f.getCanonicalFile()));
0831: FileOutputStream fos = new FileOutputStream(f);
0832: fos.close();
0833: f2 = new File(testdir + slash + "longdi~1" + slash
0834: + "longfi~1.tst");
0835: File canonicalf2 = f2.getCanonicalFile();
0836: /*
0837: * If the "short file name" doesn't exist, then assume that the
0838: * 8.3 file name compatibility is disabled.
0839: */
0840: if (canonicalf2.exists()) {
0841: assertTrue("Test 5: Incorrect File Returned: "
0842: + canonicalf2, canonicalf2.compareTo(f
0843: .getCanonicalFile()) == 0);
0844: }
0845: } finally {
0846: f.delete();
0847: f2.delete();
0848: dir.delete();
0849: testdir.delete();
0850: }
0851: }
0852: }
0853:
0854: /**
0855: * @tests java.io.File#getCanonicalPath()
0856: */
0857: public void test_getCanonicalPath() throws IOException {
0858: // Should work for Unix/Windows.
0859: String dots = "..";
0860: String base = new File(System.getProperty("user.dir"))
0861: .getCanonicalPath();
0862: if (!base.regionMatches((base.length() - 1), slash, 0, 1)) {
0863: base += slash;
0864: }
0865: File f = new File(base, "temp.tst");
0866: assertEquals("Test 1: Incorrect Path Returned.", base
0867: + "temp.tst", f.getCanonicalPath());
0868: f = new File(base + "Temp" + slash + dots + slash + "temp.tst");
0869: assertEquals("Test 2: Incorrect Path Returned.", base
0870: + "temp.tst", f.getCanonicalPath());
0871:
0872: // Finding a non-existent directory for tests 3 and 4
0873: // This is necessary because getCanonicalPath is case sensitive and
0874: // could cause a failure in the test if the directory exists but with
0875: // different case letters (e.g "Temp" and "temp")
0876: int dirNumber = 1;
0877: boolean dirExists = true;
0878: File dir1 = new File(base, String.valueOf(dirNumber));
0879: while (dirExists) {
0880: if (dir1.exists()) {
0881: dirNumber++;
0882: dir1 = new File(base, String.valueOf(dirNumber));
0883: } else {
0884: dirExists = false;
0885: }
0886: }
0887: f = new File(base + dirNumber + slash + dots + slash
0888: + dirNumber + slash + "temp.tst");
0889: assertEquals("Test 3: Incorrect Path Returned.", base
0890: + dirNumber + slash + "temp.tst", f.getCanonicalPath());
0891: f = new File(base + dirNumber + slash + "Temp" + slash + dots
0892: + slash + "Test" + slash + "temp.tst");
0893: assertEquals("Test 4: Incorrect Path Returned.", base
0894: + dirNumber + slash + "Test" + slash + "temp.tst", f
0895: .getCanonicalPath());
0896:
0897: f = new File("1234.567");
0898: assertEquals("Test 5: Incorrect Path Returned.", base
0899: + "1234.567", f.getCanonicalPath());
0900:
0901: // Test for long file names on Windows
0902: boolean onWindows = (File.separatorChar == '\\');
0903: if (onWindows) {
0904: File testdir = new File(base, "long-" + platformId);
0905: testdir.mkdir();
0906: File f1 = new File(testdir, "longfilename" + platformId
0907: + ".tst");
0908: FileOutputStream fos = new FileOutputStream(f1);
0909: File f2 = null, f3 = null, dir2 = null;
0910: try {
0911: fos.close();
0912: String dirName1 = f1.getCanonicalPath();
0913: File f4 = new File(testdir, "longfi~1.tst");
0914: /*
0915: * If the "short file name" doesn't exist, then assume that the
0916: * 8.3 file name compatibility is disabled.
0917: */
0918: if (f4.exists()) {
0919: String dirName2 = f4.getCanonicalPath();
0920: assertEquals("Test 6: Incorrect Path Returned.",
0921: dirName1, dirName2);
0922: dir2 = new File(testdir, "longdirectory"
0923: + platformId);
0924: if (!dir2.exists()) {
0925: assertTrue("Could not create dir: " + dir2,
0926: dir2.mkdir());
0927: }
0928: f2 = new File(testdir.getPath() + slash
0929: + "longdirectory" + platformId + slash
0930: + "Test" + slash + dots + slash
0931: + "longfilename.tst");
0932: FileOutputStream fos2 = new FileOutputStream(f2);
0933: fos2.close();
0934: dirName1 = f2.getCanonicalPath();
0935: f3 = new File(testdir.getPath() + slash
0936: + "longdi~1" + slash + "Test" + slash
0937: + dots + slash + "longfi~1.tst");
0938: dirName2 = f3.getCanonicalPath();
0939: assertEquals("Test 7: Incorrect Path Returned.",
0940: dirName1, dirName2);
0941: }
0942: } finally {
0943: f1.delete();
0944: if (f2 != null) {
0945: f2.delete();
0946: }
0947: if (dir2 != null) {
0948: dir2.delete();
0949: }
0950: testdir.delete();
0951: }
0952: }
0953: }
0954:
0955: /**
0956: * @tests java.io.File#getName()
0957: */
0958: public void test_getName() {
0959: File f = new File("name.tst");
0960: assertEquals("Test 1: Returned incorrect name", "name.tst", f
0961: .getName());
0962:
0963: f = new File("");
0964: assertEquals("Test 2: Returned incorrect name", "", f.getName());
0965:
0966: f.delete();
0967: }
0968:
0969: /**
0970: * @tests java.io.File#getParent()
0971: */
0972: public void test_getParent() {
0973: File f = new File("p.tst");
0974: assertNull("Incorrect path returned", f.getParent());
0975: f = new File(System.getProperty("user.home"), "p.tst");
0976: assertEquals("Incorrect path returned", System
0977: .getProperty("user.home"), f.getParent());
0978: f.delete();
0979:
0980: File f1 = new File("/directory");
0981: assertEquals("Wrong parent test 1", slash, f1.getParent());
0982: f1 = new File("/directory/file");
0983: assertEquals("Wrong parent test 2", slash + "directory", f1
0984: .getParent());
0985: f1 = new File("directory/file");
0986: assertEquals("Wrong parent test 3", "directory", f1.getParent());
0987: f1 = new File("/");
0988: assertNull("Wrong parent test 4", f1.getParent());
0989: f1 = new File("directory");
0990: assertNull("Wrong parent test 5", f1.getParent());
0991:
0992: if (File.separatorChar == '\\' && new File("d:/").isAbsolute()) {
0993: f1 = new File("d:/directory");
0994: assertEquals("Wrong parent test 1a", "d:" + slash, f1
0995: .getParent());
0996: f1 = new File("d:/directory/file");
0997: assertEquals("Wrong parent test 2a", "d:" + slash
0998: + "directory", f1.getParent());
0999: f1 = new File("d:directory/file");
1000: assertEquals("Wrong parent test 3a", "d:directory", f1
1001: .getParent());
1002: f1 = new File("d:/");
1003: assertNull("Wrong parent test 4a", f1.getParent());
1004: f1 = new File("d:directory");
1005: assertEquals("Wrong parent test 5a", "d:", f1.getParent());
1006: }
1007: }
1008:
1009: /**
1010: * @tests java.io.File#getParentFile()
1011: */
1012: public void test_getParentFile() {
1013: File f = new File("tempfile.tst");
1014: assertNull("Incorrect path returned", f.getParentFile());
1015: f = new File(System.getProperty("user.dir"), "tempfile1.tmp");
1016: File f2 = new File(System.getProperty("user.dir"),
1017: "tempfile2.tmp");
1018: File f3 = new File(System.getProperty("user.dir"),
1019: "/a/tempfile.tmp");
1020: assertEquals("Incorrect File Returned", 0, f.getParentFile()
1021: .compareTo(f2.getParentFile()));
1022: assertTrue("Incorrect File Returned", f.getParentFile()
1023: .compareTo(f3.getParentFile()) != 0);
1024: f.delete();
1025: f2.delete();
1026: f3.delete();
1027: }
1028:
1029: /**
1030: * @tests java.io.File#getPath()
1031: */
1032: public void test_getPath() {
1033: String base = System.getProperty("user.home");
1034: String fname;
1035: File f1;
1036: if (!base.regionMatches((base.length() - 1), slash, 0, 1)) {
1037: base += slash;
1038: }
1039: fname = base + "filechk.tst";
1040: f1 = new File(base, "filechk.tst");
1041: File f2 = new File("filechk.tst");
1042: File f3 = new File("c:");
1043: File f4 = new File(base + "a" + slash + slash + ".." + slash
1044: + "filechk.tst");
1045: assertEquals("getPath returned incorrect path(f1)", fname, f1
1046: .getPath());
1047: assertEquals("getPath returned incorrect path(f2)",
1048: "filechk.tst", f2.getPath());
1049: assertEquals("getPath returned incorrect path(f3)", "c:", f3
1050: .getPath());
1051: assertEquals("getPath returned incorrect path(f4)", base + "a"
1052: + slash + ".." + slash + "filechk.tst", f4.getPath());
1053: f1.delete();
1054: f2.delete();
1055: f3.delete();
1056: f4.delete();
1057:
1058: // Regression for HARMONY-444
1059: File file;
1060: String separator = File.separator;
1061:
1062: file = new File((File) null, "x/y/z");
1063: assertEquals("x" + separator + "y" + separator + "z", file
1064: .getPath());
1065:
1066: file = new File((String) null, "x/y/z");
1067: assertEquals("x" + separator + "y" + separator + "z", file
1068: .getPath());
1069:
1070: // Regression for HARMONY-829
1071: String f1ParentName = "01";
1072: f1 = new File(f1ParentName, "");
1073: assertEquals(f1ParentName, f1.getPath());
1074:
1075: String f2ParentName = "0";
1076: f2 = new File(f2ParentName, "");
1077:
1078: assertEquals(-1, f2.compareTo(f1));
1079: assertEquals(1, f1.compareTo(f2));
1080:
1081: File parent = new File(System.getProperty("user.dir"));
1082: f3 = new File(parent, "");
1083:
1084: assertEquals(parent.getPath(), f3.getPath());
1085:
1086: // Regression for HARMONY-3869
1087: File file1 = new File("", "");
1088: assertEquals(File.separator, file1.getPath());
1089:
1090: File file2 = new File(new File(""), "");
1091: assertEquals(File.separator, file2.getPath());
1092: }
1093:
1094: /**
1095: * @tests java.io.File#hashCode()
1096: */
1097: public void test_hashCode() {
1098: // Regression for HARMONY-53
1099: String mixedFname = "SoMe FiLeNaMe";
1100: File mfile = new File(mixedFname);
1101: File lfile = new File(mixedFname.toLowerCase());
1102:
1103: if (mfile.equals(lfile)) {
1104: assertTrue("Assert 0: wrong hashcode",
1105: mfile.hashCode() == lfile.hashCode());
1106: } else {
1107: assertFalse("Assert 1: wrong hashcode",
1108: mfile.hashCode() == lfile.hashCode());
1109: }
1110: }
1111:
1112: /**
1113: * @tests java.io.File#isAbsolute()
1114: */
1115: public void test_isAbsolute() {
1116: if (File.separatorChar == '\\') {
1117: File f = new File("c:\\test");
1118: File f1 = new File("\\test");
1119: // One or the other should be absolute on Windows or CE
1120: assertTrue("Absolute returned false",
1121: (f.isAbsolute() && !f1.isAbsolute())
1122: || (!f.isAbsolute() && f1.isAbsolute()));
1123: } else {
1124: File f = new File("/test");
1125: assertTrue("Absolute returned false", f.isAbsolute());
1126: }
1127: assertTrue("Non-Absolute returned true", !new File("../test")
1128: .isAbsolute());
1129: }
1130:
1131: /**
1132: * @tests java.io.File#isDirectory()
1133: */
1134: public void test_isDirectory() {
1135: String base = System.getProperty("user.dir");
1136: if (!base.regionMatches((base.length() - 1), slash, 0, 1)) {
1137: base += slash;
1138: }
1139: File f = new File(base);
1140: assertTrue("Test 1: Directory Returned False", f.isDirectory());
1141: f = new File(base + "zxzxzxz" + platformId);
1142: assertTrue("Test 2: (Not Created) Directory Returned True.", !f
1143: .isDirectory());
1144: f.mkdir();
1145: try {
1146: assertTrue("Test 3: Directory Returned False.", f
1147: .isDirectory());
1148: } finally {
1149: f.delete();
1150: }
1151: }
1152:
1153: /**
1154: * @tests java.io.File#isFile()
1155: */
1156: public void test_isFile() throws IOException {
1157: String base = System.getProperty("user.dir");
1158: File f = new File(base);
1159: assertTrue("Directory Returned True As Being A File.", !f
1160: .isFile());
1161: if (!base.regionMatches((base.length() - 1), slash, 0, 1)) {
1162: base += slash;
1163: }
1164: f = new File(base, platformId + "amiafile");
1165: assertTrue("Non-existent File Returned True", !f.isFile());
1166: FileOutputStream fos = new FileOutputStream(f);
1167: fos.close();
1168: assertTrue("File returned false", f.isFile());
1169: f.delete();
1170: }
1171:
1172: /**
1173: * @tests java.io.File#isHidden()
1174: */
1175: public void test_isHidden() throws IOException,
1176: InterruptedException {
1177: boolean onUnix = File.separatorChar == '/';
1178: File f = File.createTempFile("hyts_", ".tmp");
1179: // On Unix hidden files are marked with a "." at the beginning
1180: // of the file name.
1181: if (onUnix) {
1182: File f2 = new File(".test.tst" + platformId);
1183: FileOutputStream fos2 = new FileOutputStream(f2);
1184: fos2.close();
1185: assertTrue("File returned hidden on Unix", !f.isHidden());
1186: assertTrue("File returned visible on Unix", f2.isHidden());
1187: assertTrue("File did not delete.", f2.delete());
1188: } else {
1189: // For windows, the file is being set hidden by the attrib
1190: // command.
1191: Runtime r = Runtime.getRuntime();
1192: assertTrue("File returned hidden", !f.isHidden());
1193: Process p = r.exec("attrib +h \"" + f.getAbsolutePath()
1194: + "\"");
1195: p.waitFor();
1196: assertTrue("File returned visible", f.isHidden());
1197: p = r.exec("attrib -h \"" + f.getAbsolutePath() + "\"");
1198: p.waitFor();
1199: assertTrue("File returned hidden", !f.isHidden());
1200: }
1201: f.delete();
1202: }
1203:
1204: /**
1205: * @tests java.io.File#lastModified()
1206: */
1207: public void test_lastModified() throws IOException {
1208: File f = new File(System.getProperty("java.io.tmpdir"),
1209: platformId + "lModTest.tst");
1210: f.delete();
1211: long lastModifiedTime = f.lastModified();
1212: assertEquals("LastModified Time Should Have Returned 0.", 0,
1213: lastModifiedTime);
1214: FileOutputStream fos = new FileOutputStream(f);
1215: fos.close();
1216: f.setLastModified(315550800000L);
1217: lastModifiedTime = f.lastModified();
1218: assertEquals("LastModified Time Incorrect", 315550800000L,
1219: lastModifiedTime);
1220: f.delete();
1221:
1222: // Regression for HARMONY-2146
1223: f = new File("/../");
1224: assertTrue(f.lastModified() > 0);
1225: }
1226:
1227: /**
1228: * @tests java.io.File#length()
1229: */
1230: public void test_length() throws IOException {
1231: File f = new File(System.getProperty("user.dir"), platformId
1232: + "input.tst");
1233: assertEquals("File Length Should Have Returned 0.", 0, f
1234: .length());
1235: FileOutputStream fos = new FileOutputStream(f);
1236: fos.write(fileString.getBytes());
1237: fos.close();
1238: assertEquals("Incorrect file length returned", fileString
1239: .length(), f.length());
1240: f.delete();
1241:
1242: // regression test for HARMONY-1497
1243: f = File.createTempFile("test", "tmp");
1244: f.deleteOnExit();
1245: RandomAccessFile raf = new RandomAccessFile(f, "rwd");
1246: raf.write(0x41);
1247: assertEquals(1, f.length());
1248: }
1249:
1250: /**
1251: * @tests java.io.File#list()
1252: */
1253: public void test_list() throws IOException {
1254: String base = System.getProperty("user.dir");
1255: // Old test left behind "garbage files" so this time it creates a
1256: // directory that is guaranteed not to already exist (and deletes it
1257: // afterward.)
1258: int dirNumber = 1;
1259: boolean dirExists = true;
1260: File dir = null;
1261: dir = new File(base, platformId + String.valueOf(dirNumber));
1262: while (dirExists) {
1263: if (dir.exists()) {
1264: dirNumber++;
1265: dir = new File(base, String.valueOf(dirNumber));
1266: } else {
1267: dirExists = false;
1268: }
1269: }
1270:
1271: String[] flist = dir.list();
1272:
1273: assertNull("Method list() Should Have Returned null.", flist);
1274:
1275: assertTrue("Could not create parent directory for list test",
1276: dir.mkdir());
1277:
1278: String[] files = { "mtzz1.xx", "mtzz2.xx", "mtzz3.yy",
1279: "mtzz4.yy" };
1280: try {
1281: assertEquals(
1282: "Method list() Should Have Returned An Array Of Length 0.",
1283: 0, dir.list().length);
1284:
1285: File file = new File(dir, "notADir.tst");
1286: try {
1287: FileOutputStream fos = new FileOutputStream(file);
1288: fos.close();
1289: assertNull(
1290: "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
1291: file.list());
1292: } finally {
1293: file.delete();
1294: }
1295:
1296: for (int i = 0; i < files.length; i++) {
1297: File f = new File(dir, files[i]);
1298: FileOutputStream fos = new FileOutputStream(f);
1299: fos.close();
1300: }
1301:
1302: flist = dir.list();
1303: if (flist.length != files.length) {
1304: fail("Incorrect list returned");
1305: }
1306:
1307: // Checking to make sure the correct files were are listed in the
1308: // array.
1309: boolean[] check = new boolean[flist.length];
1310: for (int i = 0; i < check.length; i++) {
1311: check[i] = false;
1312: }
1313: for (int i = 0; i < files.length; i++) {
1314: for (int j = 0; j < flist.length; j++) {
1315: if (flist[j].equals(files[i])) {
1316: check[i] = true;
1317: break;
1318: }
1319: }
1320: }
1321: int checkCount = 0;
1322: for (int i = 0; i < check.length; i++) {
1323: if (check[i] == false) {
1324: checkCount++;
1325: }
1326: }
1327: assertEquals("Invalid file returned in listing", 0,
1328: checkCount);
1329:
1330: for (int i = 0; i < files.length; i++) {
1331: File f = new File(dir, files[i]);
1332: f.delete();
1333: }
1334:
1335: assertTrue(
1336: "Could not delete parent directory for list test.",
1337: dir.delete());
1338: } finally {
1339: for (int i = 0; i < files.length; i++) {
1340: File f = new File(dir, files[i]);
1341: f.delete();
1342: }
1343: dir.delete();
1344: }
1345: }
1346:
1347: /**
1348: * @tests java.io.File#listFiles()
1349: */
1350: public void test_listFiles() throws IOException,
1351: InterruptedException {
1352: String base = System.getProperty("user.dir");
1353: // Finding a non-existent directory to create.
1354: int dirNumber = 1;
1355: boolean dirExists = true;
1356: File dir = new File(base, platformId
1357: + String.valueOf(dirNumber));
1358: // Making sure that the directory does not exist.
1359: while (dirExists) {
1360: // If the directory exists, add one to the directory number
1361: // (making it a new directory name.)
1362: if (dir.exists()) {
1363: dirNumber++;
1364: dir = new File(base, String.valueOf(dirNumber));
1365: } else {
1366: dirExists = false;
1367: }
1368: }
1369: // Test for attempting to call listFiles on a non-existent directory.
1370: assertNull("listFiles Should Return Null.", dir.listFiles());
1371:
1372: assertTrue("Failed To Create Parent Directory.", dir.mkdir());
1373:
1374: String[] files = { "1.tst", "2.tst", "3.tst", "" };
1375: try {
1376: assertEquals(
1377: "listFiles Should Return An Array Of Length 0.", 0,
1378: dir.listFiles().length);
1379:
1380: File file = new File(dir, "notADir.tst");
1381: try {
1382: FileOutputStream fos = new FileOutputStream(file);
1383: fos.close();
1384: assertNull(
1385: "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
1386: file.listFiles());
1387: } finally {
1388: file.delete();
1389: }
1390:
1391: for (int i = 0; i < (files.length - 1); i++) {
1392: File f = new File(dir, files[i]);
1393: FileOutputStream fos = new FileOutputStream(f);
1394: fos.close();
1395: }
1396:
1397: new File(dir, "doesNotExist.tst");
1398: File[] flist = dir.listFiles();
1399:
1400: // Test to make sure that only the 3 files that were created are
1401: // listed.
1402: assertEquals("Incorrect Number Of Files Returned.", 3,
1403: flist.length);
1404:
1405: // Test to make sure that listFiles can read hidden files.
1406: boolean onUnix = File.separatorChar == '/';
1407: boolean onWindows = File.separatorChar == '\\';
1408: if (onWindows) {
1409: files[3] = "4.tst";
1410: File f = new File(dir, "4.tst");
1411: FileOutputStream fos = new FileOutputStream(f);
1412: fos.close();
1413: Runtime r = Runtime.getRuntime();
1414: Process p = r.exec("attrib +h \"" + f.getPath() + "\"");
1415: p.waitFor();
1416: }
1417: if (onUnix) {
1418: files[3] = ".4.tst";
1419: File f = new File(dir, ".4.tst");
1420: FileOutputStream fos = new FileOutputStream(f);
1421: fos.close();
1422: }
1423: flist = dir.listFiles();
1424: assertEquals("Incorrect Number Of Files Returned.", 4,
1425: flist.length);
1426:
1427: // Checking to make sure the correct files were are listed in
1428: // the array.
1429: boolean[] check = new boolean[flist.length];
1430: for (int i = 0; i < check.length; i++) {
1431: check[i] = false;
1432: }
1433: for (int i = 0; i < files.length; i++) {
1434: for (int j = 0; j < flist.length; j++) {
1435: if (flist[j].getName().equals(files[i])) {
1436: check[i] = true;
1437: break;
1438: }
1439: }
1440: }
1441: int checkCount = 0;
1442: for (int i = 0; i < check.length; i++) {
1443: if (check[i] == false) {
1444: checkCount++;
1445: }
1446: }
1447: assertEquals("Invalid file returned in listing", 0,
1448: checkCount);
1449:
1450: if (onWindows) {
1451: Runtime r = Runtime.getRuntime();
1452: Process p = r.exec("attrib -h \""
1453: + new File(dir, files[3]).getPath() + "\"");
1454: p.waitFor();
1455: }
1456:
1457: for (int i = 0; i < files.length; i++) {
1458: File f = new File(dir, files[i]);
1459: f.delete();
1460: }
1461: assertTrue("Parent Directory Not Deleted.", dir.delete());
1462: } finally {
1463: for (int i = 0; i < files.length; i++) {
1464: File f = new File(dir, files[i]);
1465: f.delete();
1466: }
1467: dir.delete();
1468: }
1469: }
1470:
1471: /**
1472: * @tests java.io.File#listFiles(java.io.FileFilter)
1473: */
1474: public void test_listFilesLjava_io_FileFilter() throws IOException {
1475: String base = System.getProperty("java.io.tmpdir");
1476: // Finding a non-existent directory to create.
1477: int dirNumber = 1;
1478: boolean dirExists = true;
1479: File baseDir = new File(base, platformId
1480: + String.valueOf(dirNumber));
1481: // Making sure that the directory does not exist.
1482: while (dirExists) {
1483: // If the directory exists, add one to the directory number (making
1484: // it a new directory name.)
1485: if (baseDir.exists()) {
1486: dirNumber++;
1487: baseDir = new File(base, String.valueOf(dirNumber));
1488: } else {
1489: dirExists = false;
1490: }
1491: }
1492:
1493: // Creating a filter that catches directories.
1494: FileFilter dirFilter = new FileFilter() {
1495: public boolean accept(File f) {
1496: return f.isDirectory();
1497: }
1498: };
1499:
1500: assertNull("listFiles Should Return Null.", baseDir
1501: .listFiles(dirFilter));
1502:
1503: assertTrue("Failed To Create Parent Directory.", baseDir
1504: .mkdir());
1505:
1506: File dir1 = null;
1507: String[] files = { "1.tst", "2.tst", "3.tst" };
1508: try {
1509: assertEquals(
1510: "listFiles Should Return An Array Of Length 0.", 0,
1511: baseDir.listFiles(dirFilter).length);
1512:
1513: File file = new File(baseDir, "notADir.tst");
1514: try {
1515: FileOutputStream fos = new FileOutputStream(file);
1516: fos.close();
1517: assertNull(
1518: "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
1519: file.listFiles(dirFilter));
1520: } finally {
1521: file.delete();
1522: }
1523:
1524: for (int i = 0; i < files.length; i++) {
1525: File f = new File(baseDir, files[i]);
1526: FileOutputStream fos = new FileOutputStream(f);
1527: fos.close();
1528: }
1529: dir1 = new File(baseDir, "Temp1");
1530: dir1.mkdir();
1531:
1532: // Creating a filter that catches files.
1533: FileFilter fileFilter = new FileFilter() {
1534: public boolean accept(File f) {
1535: return f.isFile();
1536: }
1537: };
1538:
1539: // Test to see if the correct number of directories are returned.
1540: File[] directories = baseDir.listFiles(dirFilter);
1541: assertEquals("Incorrect Number Of Directories Returned.",
1542: 1, directories.length);
1543:
1544: // Test to see if the directory was saved with the correct name.
1545: assertEquals("Incorrect Directory Returned.", 0,
1546: directories[0].compareTo(dir1));
1547:
1548: // Test to see if the correct number of files are returned.
1549: File[] flist = baseDir.listFiles(fileFilter);
1550: assertEquals("Incorrect Number Of Files Returned.",
1551: files.length, flist.length);
1552:
1553: // Checking to make sure the correct files were are listed in the
1554: // array.
1555: boolean[] check = new boolean[flist.length];
1556: for (int i = 0; i < check.length; i++) {
1557: check[i] = false;
1558: }
1559: for (int i = 0; i < files.length; i++) {
1560: for (int j = 0; j < flist.length; j++) {
1561: if (flist[j].getName().equals(files[i])) {
1562: check[i] = true;
1563: break;
1564: }
1565: }
1566: }
1567: int checkCount = 0;
1568: for (int i = 0; i < check.length; i++) {
1569: if (check[i] == false) {
1570: checkCount++;
1571: }
1572: }
1573: assertEquals("Invalid file returned in listing", 0,
1574: checkCount);
1575:
1576: for (int i = 0; i < files.length; i++) {
1577: File f = new File(baseDir, files[i]);
1578: f.delete();
1579: }
1580: dir1.delete();
1581: assertTrue("Parent Directory Not Deleted.", baseDir
1582: .delete());
1583: } finally {
1584: for (int i = 0; i < files.length; i++) {
1585: File f = new File(baseDir, files[i]);
1586: f.delete();
1587: }
1588: if (dir1 != null) {
1589: dir1.delete();
1590: }
1591: baseDir.delete();
1592: }
1593: }
1594:
1595: /**
1596: * @tests java.io.File#listFiles(java.io.FilenameFilter)
1597: */
1598: public void test_listFilesLjava_io_FilenameFilter()
1599: throws IOException {
1600: String base = System.getProperty("java.io.tmpdir");
1601: // Finding a non-existent directory to create.
1602: int dirNumber = 1;
1603: boolean dirExists = true;
1604: File dir = new File(base, platformId
1605: + String.valueOf(dirNumber));
1606: // Making sure that the directory does not exist.
1607: while (dirExists) {
1608: // If the directory exists, add one to the directory number (making
1609: // it a new directory name.)
1610: if (dir.exists()) {
1611: dirNumber++;
1612: dir = new File(base, platformId
1613: + String.valueOf(dirNumber));
1614: } else {
1615: dirExists = false;
1616: }
1617: }
1618:
1619: // Creating a filter that catches "*.tst" files.
1620: FilenameFilter tstFilter = new FilenameFilter() {
1621: public boolean accept(File f, String fileName) {
1622: return fileName.endsWith(".tst");
1623: }
1624: };
1625:
1626: assertNull("listFiles Should Return Null.", dir
1627: .listFiles(tstFilter));
1628:
1629: assertTrue("Failed To Create Parent Directory.", dir.mkdir());
1630:
1631: String[] files = { "1.tst", "2.tst", "3.tmp" };
1632: try {
1633: assertEquals(
1634: "listFiles Should Return An Array Of Length 0.", 0,
1635: dir.listFiles(tstFilter).length);
1636:
1637: File file = new File(dir, "notADir.tst");
1638: try {
1639: FileOutputStream fos = new FileOutputStream(file);
1640: fos.close();
1641: assertNull(
1642: "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
1643: file.listFiles(tstFilter));
1644: } finally {
1645: file.delete();
1646: }
1647:
1648: for (int i = 0; i < files.length; i++) {
1649: File f = new File(dir, files[i]);
1650: FileOutputStream fos = new FileOutputStream(f);
1651: fos.close();
1652: }
1653:
1654: // Creating a filter that catches "*.tmp" files.
1655: FilenameFilter tmpFilter = new FilenameFilter() {
1656: public boolean accept(File f, String fileName) {
1657: // If the suffix is ".tmp" then send it to the array
1658: if (fileName.endsWith(".tmp")) {
1659: return true;
1660: } else {
1661: return false;
1662: }
1663: }
1664: };
1665:
1666: // Tests to see if the correct number of files were returned.
1667: File[] flist = dir.listFiles(tstFilter);
1668: assertEquals(
1669: "Incorrect Number Of Files Passed Through tstFilter.",
1670: 2, flist.length);
1671: for (int i = 0; i < flist.length; i++) {
1672: assertTrue(
1673: "File Should Not Have Passed The tstFilter.",
1674: flist[i].getPath().endsWith(".tst"));
1675: }
1676:
1677: flist = dir.listFiles(tmpFilter);
1678: assertEquals(
1679: "Incorrect Number Of Files Passed Through tmpFilter.",
1680: 1, flist.length);
1681: assertTrue("File Should Not Have Passed The tmpFilter.",
1682: flist[0].getPath().endsWith(".tmp"));
1683:
1684: for (int i = 0; i < files.length; i++) {
1685: File f = new File(dir, files[i]);
1686: f.delete();
1687: }
1688: assertTrue("Parent Directory Not Deleted.", dir.delete());
1689: } finally {
1690: for (int i = 0; i < files.length; i++) {
1691: File f = new File(dir, files[i]);
1692: f.delete();
1693: }
1694: dir.delete();
1695: }
1696: }
1697:
1698: /**
1699: * @tests java.io.File#list(java.io.FilenameFilter)
1700: */
1701: public void test_listLjava_io_FilenameFilter() throws IOException {
1702: String base = System.getProperty("user.dir");
1703: // Old test left behind "garbage files" so this time it creates a
1704: // directory that is guaranteed not to already exist (and deletes it
1705: // afterward.)
1706: int dirNumber = 1;
1707: boolean dirExists = true;
1708: File dir = new File(base, platformId
1709: + String.valueOf(dirNumber));
1710: while (dirExists) {
1711: if (dir.exists()) {
1712: dirNumber++;
1713: dir = new File(base, String.valueOf(dirNumber));
1714: } else {
1715: dirExists = false;
1716: }
1717: }
1718:
1719: FilenameFilter filter = new FilenameFilter() {
1720: public boolean accept(File dir, String name) {
1721: return !name.equals("mtzz1.xx");
1722: }
1723: };
1724:
1725: String[] flist = dir.list(filter);
1726: assertNull(
1727: "Method list(FilenameFilter) Should Have Returned Null.",
1728: flist);
1729:
1730: assertTrue("Could not create parent directory for test", dir
1731: .mkdir());
1732:
1733: String[] files = { "mtzz1.xx", "mtzz2.xx", "mtzz3.yy",
1734: "mtzz4.yy" };
1735: try {
1736: /*
1737: * Do not return null when trying to use list(Filename Filter) on a
1738: * file rather than a directory. All other "list" methods return
1739: * null for this test case.
1740: */
1741: /*
1742: * File file = new File(dir, "notADir.tst"); try { FileOutputStream
1743: * fos = new FileOutputStream(file); fos.close(); } catch
1744: * (IOException e) { fail("Unexpected IOException During Test."); }
1745: * flist = dir.list(filter); assertNull("listFiles Should Have
1746: * Returned Null When Used On A File Instead Of A Directory.",
1747: * flist); file.delete();
1748: */
1749:
1750: flist = dir.list(filter);
1751: assertEquals("Array Of Length 0 Should Have Returned.", 0,
1752: flist.length);
1753:
1754: for (int i = 0; i < files.length; i++) {
1755: File f = new File(dir, files[i]);
1756: FileOutputStream fos = new FileOutputStream(f);
1757: fos.close();
1758: }
1759:
1760: flist = dir.list(filter);
1761:
1762: assertEquals("Incorrect list returned", flist.length,
1763: files.length - 1);
1764:
1765: // Checking to make sure the correct files were are listed in the
1766: // array.
1767: boolean[] check = new boolean[flist.length];
1768: for (int i = 0; i < check.length; i++) {
1769: check[i] = false;
1770: }
1771: String[] wantedFiles = { "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" };
1772: for (int i = 0; i < wantedFiles.length; i++) {
1773: for (int j = 0; j < flist.length; j++) {
1774: if (flist[j].equals(wantedFiles[i])) {
1775: check[i] = true;
1776: break;
1777: }
1778: }
1779: }
1780: int checkCount = 0;
1781: for (int i = 0; i < check.length; i++) {
1782: if (check[i] == false) {
1783: checkCount++;
1784: }
1785: }
1786: assertEquals("Invalid file returned in listing", 0,
1787: checkCount);
1788:
1789: for (int i = 0; i < files.length; i++) {
1790: File f = new File(dir, files[i]);
1791: f.delete();
1792: }
1793: assertTrue("Could not delete parent directory for test.",
1794: dir.delete());
1795: } finally {
1796: for (int i = 0; i < files.length; i++) {
1797: File f = new File(dir, files[i]);
1798: f.delete();
1799: }
1800: dir.delete();
1801: }
1802: }
1803:
1804: /**
1805: * @tests java.io.File#listRoots()
1806: */
1807: public void test_listRoots() {
1808: File[] roots = File.listRoots();
1809: boolean onUnix = File.separatorChar == '/';
1810: boolean onWindows = File.separatorChar == '\\';
1811: if (onUnix) {
1812: assertEquals("Incorrect Number Of Root Directories.", 1,
1813: roots.length);
1814: String fileLoc = roots[0].getPath();
1815: assertTrue("Incorrect Root Directory Returned.", fileLoc
1816: .startsWith(slash));
1817: } else if (onWindows) {
1818: // Need better test for Windows
1819: assertTrue("Incorrect Number Of Root Directories.",
1820: roots.length > 0);
1821: }
1822: }
1823:
1824: /**
1825: * @tests java.io.File#mkdir()
1826: */
1827: public void test_mkdir() throws IOException {
1828: String base = System.getProperty("user.dir");
1829: // Old test left behind "garbage files" so this time it creates a
1830: // directory that is guaranteed not to already exist (and deletes it
1831: // afterward.)
1832: int dirNumber = 1;
1833: boolean dirExists = true;
1834: File dir = new File(base, String.valueOf(dirNumber));
1835: while (dirExists) {
1836: if (dir.exists()) {
1837: dirNumber++;
1838: dir = new File(base, String.valueOf(dirNumber));
1839: } else {
1840: dirExists = false;
1841: }
1842: }
1843:
1844: assertTrue("mkdir failed", dir.mkdir());
1845: assertTrue("mkdir worked but exists check failed", dir.exists());
1846: dir.deleteOnExit();
1847:
1848: String longDirName = "abcdefghijklmnopqrstuvwx";// 24 chars
1849: String newbase = new String(dir + File.separator);
1850: StringBuilder sb = new StringBuilder(dir + File.separator);
1851: StringBuilder sb2 = new StringBuilder(dir + File.separator);
1852:
1853: // Test make a long path
1854: while (dir.getCanonicalPath().length() < 256 - longDirName
1855: .length()) {
1856: sb.append(longDirName + File.separator);
1857: dir = new File(sb.toString());
1858: assertTrue("mkdir failed", dir.mkdir());
1859: assertTrue("mkdir worked but exists check failed", dir
1860: .exists());
1861: dir.deleteOnExit();
1862: }
1863:
1864: while (dir.getCanonicalPath().length() < 256) {
1865: sb.append(0);
1866: dir = new File(sb.toString());
1867: assertTrue("mkdir " + dir.getCanonicalPath().length()
1868: + " failed", dir.mkdir());
1869: assertTrue("mkdir " + dir.getCanonicalPath().length()
1870: + " worked but exists check failed", dir.exists());
1871: dir.deleteOnExit();
1872: }
1873: dir = new File(sb2.toString());
1874: // Test make many paths
1875: while (dir.getCanonicalPath().length() < 256) {
1876: sb2.append(0);
1877: dir = new File(sb2.toString());
1878: assertTrue("mkdir " + dir.getCanonicalPath().length()
1879: + " failed", dir.mkdir());
1880: assertTrue("mkdir " + dir.getCanonicalPath().length()
1881: + " worked but exists check failed", dir.exists());
1882: dir.deleteOnExit();
1883: }
1884:
1885: // Regression test for HARMONY-3656
1886: String[] ss = { "dir\u3400", "abc", "abc@123", "!@#$%^&",
1887: "~\u4E00!\u4E8C@\u4E09$", "\u56DB\u4E94\u516D",
1888: "\u4E03\u516B\u4E5D" };
1889: for (int i = 0; i < ss.length; i++) {
1890: dir = new File(newbase, ss[i]);
1891: assertTrue("mkdir " + dir.getCanonicalPath() + " failed",
1892: dir.mkdir());
1893: assertTrue("mkdir " + dir.getCanonicalPath()
1894: + " worked but exists check failed", dir.exists());
1895: dir.deleteOnExit();
1896: }
1897: }
1898:
1899: /**
1900: * @tests java.io.File#mkdirs()
1901: */
1902: public void test_mkdirs() {
1903: String userHome = System.getProperty("user.dir");
1904: if (!userHome.endsWith(slash)) {
1905: userHome += slash;
1906: }
1907: File f = new File(userHome + "mdtest" + platformId + slash
1908: + "mdtest2", "p.tst");
1909: File g = new File(userHome + "mdtest" + platformId + slash
1910: + "mdtest2");
1911: File h = new File(userHome + "mdtest" + platformId);
1912: f.mkdirs();
1913: try {
1914: assertTrue("Base Directory not created", h.exists());
1915: assertTrue("Directories not created", g.exists());
1916: assertTrue("File not created", f.exists());
1917: } finally {
1918: f.delete();
1919: g.delete();
1920: h.delete();
1921: }
1922: }
1923:
1924: /**
1925: * @tests java.io.File#renameTo(java.io.File)
1926: */
1927: public void test_renameToLjava_io_File() throws IOException {
1928: String base = System.getProperty("user.dir");
1929: File dir = new File(base, platformId);
1930: dir.mkdir();
1931: File f = new File(dir, "xxx.xxx");
1932: File rfile = new File(dir, "yyy.yyy");
1933: File f2 = new File(dir, "zzz.zzz");
1934: try {
1935: FileOutputStream fos = new FileOutputStream(f);
1936: fos.write(fileString.getBytes());
1937: fos.close();
1938: long lengthOfFile = f.length();
1939:
1940: rfile.delete(); // in case it already exists
1941:
1942: assertTrue("Test 1: File Rename Failed", f.renameTo(rfile));
1943: assertTrue("Test 2: File Rename Failed.", rfile.exists());
1944: assertEquals("Test 3: Size Of File Changed.", lengthOfFile,
1945: rfile.length());
1946:
1947: fos = new FileOutputStream(rfile);
1948: fos.close();
1949:
1950: f2.delete(); // in case it already exists
1951: assertTrue("Test 4: File Rename Failed", rfile.renameTo(f2));
1952: assertTrue("Test 5: File Rename Failed.", f2.exists());
1953: } finally {
1954: f.delete();
1955: rfile.delete();
1956: f2.delete();
1957: dir.delete();
1958: }
1959: }
1960:
1961: /**
1962: * @tests java.io.File#setLastModified(long)
1963: */
1964: public void test_setLastModifiedJ() throws IOException {
1965: File f1 = null;
1966: try {
1967: f1 = new File(Support_PlatformFile.getNewPlatformFile(
1968: "hyts_tf_slm", ".tmp"));
1969: f1.createNewFile();
1970: long orgTime = f1.lastModified();
1971: // Subtracting 100 000 milliseconds from the orgTime of File f1
1972: f1.setLastModified(orgTime - 100000);
1973: long lastModified = f1.lastModified();
1974: assertEquals("Test 1: LastModifed time incorrect",
1975: orgTime - 100000, lastModified);
1976: // Subtracting 10 000 000 milliseconds from the orgTime of File f1
1977: f1.setLastModified(orgTime - 10000000);
1978: lastModified = f1.lastModified();
1979: assertEquals("Test 2: LastModifed time incorrect",
1980: orgTime - 10000000, lastModified);
1981: // Adding 100 000 milliseconds to the orgTime of File f1
1982: f1.setLastModified(orgTime + 100000);
1983: lastModified = f1.lastModified();
1984: assertEquals("Test 3: LastModifed time incorrect",
1985: orgTime + 100000, lastModified);
1986: // Adding 10 000 000 milliseconds from the orgTime of File f1
1987: f1.setLastModified(orgTime + 10000000);
1988: lastModified = f1.lastModified();
1989: assertEquals("Test 4: LastModifed time incorrect",
1990: orgTime + 10000000, lastModified);
1991: // Trying to set time to an exact number
1992: f1.setLastModified(315550800000L);
1993: lastModified = f1.lastModified();
1994: assertEquals("Test 5: LastModified time incorrect",
1995: 315550800000L, lastModified);
1996: String osName = System.getProperty("os.name", "unknown");
1997: if (osName.equals("Windows 2000")
1998: || osName.equals("Windows NT")) {
1999: // Trying to set time to a large exact number
2000: boolean result = f1.setLastModified(4354837199000L);
2001: long next = f1.lastModified();
2002: // Dec 31 23:59:59 EST 2107 is overflow on FAT file systems, and
2003: // the call fails
2004: if (result) {
2005: assertEquals("Test 6: LastModified time incorrect",
2006: 4354837199000L, next);
2007: }
2008: }
2009: // Trying to set time to a negative number
2010: try {
2011: f1.setLastModified(-25);
2012: fail("IllegalArgumentException Not Thrown.");
2013: } catch (IllegalArgumentException e) {
2014: }
2015: } finally {
2016: if (f1 != null) {
2017: f1.delete();
2018: }
2019: }
2020: }
2021:
2022: /**
2023: * @tests java.io.File#setReadOnly()
2024: */
2025: public void test_setReadOnly() throws IOException,
2026: InterruptedException {
2027: File f1 = null;
2028: File f2 = null;
2029: try {
2030: f1 = File.createTempFile("hyts_tf", ".tmp");
2031: f2 = File.createTempFile("hyts_tf", ".tmp");
2032: // Assert is flawed because canWrite does not work.
2033: // assertTrue("File f1 Is Set To ReadOnly." , f1.canWrite());
2034: f1.setReadOnly();
2035: // Assert is flawed because canWrite does not work.
2036: // assertTrue("File f1 Is Not Set To ReadOnly." , !f1.canWrite());
2037: try {
2038: // Attempt to write to a file that is setReadOnly.
2039: new FileOutputStream(f1);
2040: fail("IOException not thrown.");
2041: } catch (IOException e) {
2042: // Expected
2043: }
2044: Runtime r = Runtime.getRuntime();
2045: Process p;
2046: boolean onUnix = File.separatorChar == '/';
2047: if (onUnix) {
2048: p = r.exec("chmod +w " + f1.getAbsolutePath());
2049: } else {
2050: p = r
2051: .exec("attrib -r \"" + f1.getAbsolutePath()
2052: + "\"");
2053: }
2054: p.waitFor();
2055: // Assert is flawed because canWrite does not work.
2056: // assertTrue("File f1 Is Set To ReadOnly." , f1.canWrite());
2057: FileOutputStream fos = new FileOutputStream(f1);
2058: fos.write(fileString.getBytes());
2059: fos.close();
2060: assertTrue("File Was Not Able To Be Written To.", f1
2061: .length() == fileString.length());
2062: assertTrue("File f1 Did Not Delete", f1.delete());
2063:
2064: // Assert is flawed because canWrite does not work.
2065: // assertTrue("File f2 Is Set To ReadOnly." , f2.canWrite());
2066: fos = new FileOutputStream(f2);
2067: // Write to a file.
2068: fos.write(fileString.getBytes());
2069: fos.close();
2070: f2.setReadOnly();
2071: // Assert is flawed because canWrite does not work.
2072: // assertTrue("File f2 Is Not Set To ReadOnly." , !f2.canWrite());
2073: try {
2074: // Attempt to write to a file that has previously been written
2075: // to.
2076: // and is now set to read only.
2077: fos = new FileOutputStream(f2);
2078: fail("IOException not thrown.");
2079: } catch (IOException e) {
2080: // Expected
2081: }
2082: r = Runtime.getRuntime();
2083: if (onUnix) {
2084: p = r.exec("chmod +w " + f2.getAbsolutePath());
2085: } else {
2086: p = r
2087: .exec("attrib -r \"" + f2.getAbsolutePath()
2088: + "\"");
2089: }
2090: p.waitFor();
2091: assertTrue("File f2 Is Set To ReadOnly.", f2.canWrite());
2092: fos = new FileOutputStream(f2);
2093: fos.write(fileString.getBytes());
2094: fos.close();
2095: f2.setReadOnly();
2096: assertTrue("File f2 Did Not Delete", f2.delete());
2097: // Similarly, trying to delete a read-only directory should succeed
2098: f2 = new File(System.getProperty("user.dir"), "deltestdir");
2099: f2.mkdir();
2100: f2.setReadOnly();
2101: assertTrue("Directory f2 Did Not Delete", f2.delete());
2102: assertTrue("Directory f2 Did Not Delete", !f2.exists());
2103: } finally {
2104: if (f1 != null) {
2105: f1.delete();
2106: }
2107: if (f2 != null) {
2108: f2.delete();
2109: }
2110: }
2111: }
2112:
2113: /**
2114: * @tests java.io.File#toString()
2115: */
2116: public void test_toString() {
2117: String fileName = System.getProperty("user.home") + slash
2118: + "input.tst";
2119: File f = new File(fileName);
2120: assertEquals("Incorrect string returned", fileName, f
2121: .toString());
2122:
2123: if (File.separatorChar == '\\') {
2124: String result = new File("c:\\").toString();
2125: assertEquals("Removed backslash", "c:\\", result);
2126: }
2127: }
2128:
2129: /**
2130: * @tests java.io.File#toURI()
2131: */
2132: public void test_toURI() throws URISyntaxException {
2133: // Need a directory that exists
2134: File dir = new File(System.getProperty("user.dir"));
2135:
2136: // Test for toURI when the file is a directory.
2137: String newURIPath = dir.getAbsolutePath();
2138: newURIPath = newURIPath.replace(File.separatorChar, '/');
2139: if (!newURIPath.startsWith("/")) {
2140: newURIPath = "/" + newURIPath;
2141: }
2142: if (!newURIPath.endsWith("/")) {
2143: newURIPath += '/';
2144: }
2145:
2146: URI uri = dir.toURI();
2147: assertEquals("Test 1A: Incorrect URI Returned.", dir
2148: .getAbsoluteFile(), new File(uri));
2149: assertEquals("Test 1B: Incorrect URI Returned.", new URI(
2150: "file", null, newURIPath, null, null), uri);
2151:
2152: // Test for toURI with a file name with illegal chars.
2153: File f = new File(dir, "te% \u20ac st.tst");
2154: newURIPath = f.getAbsolutePath();
2155: newURIPath = newURIPath.replace(File.separatorChar, '/');
2156: if (!newURIPath.startsWith("/")) {
2157: newURIPath = "/" + newURIPath;
2158: }
2159:
2160: uri = f.toURI();
2161: assertEquals("Test 2A: Incorrect URI Returned.", f
2162: .getAbsoluteFile(), new File(uri));
2163: assertEquals("Test 2B: Incorrect URI Returned.", new URI(
2164: "file", null, newURIPath, null, null), uri);
2165:
2166: // Regression test for HARMONY-3207
2167: dir = new File(""); // current directory
2168: uri = dir.toURI();
2169: assertTrue("Test current dir: URI does not end with slash.",
2170: uri.toString().endsWith("/"));
2171: }
2172:
2173: /**
2174: * @tests java.io.File#toURL()
2175: */
2176: public void test_toURL() throws MalformedURLException {
2177: // Need a directory that exists
2178: File dir = new File(System.getProperty("user.dir"));
2179:
2180: // Test for toURL when the file is a directory.
2181: String newDirURL = dir.getAbsolutePath();
2182: newDirURL = newDirURL.replace(File.separatorChar, '/');
2183: if (newDirURL.startsWith("/")) {
2184: newDirURL = "file:" + newDirURL;
2185: } else {
2186: newDirURL = "file:/" + newDirURL;
2187: }
2188: if (!newDirURL.endsWith("/")) {
2189: newDirURL += '/';
2190: }
2191: assertEquals("Test 1: Incorrect URL Returned.", dir.toURL()
2192: .toString(), newDirURL);
2193:
2194: // Test for toURL with a file.
2195: File f = new File(dir, "test.tst");
2196: String newURL = f.getAbsolutePath();
2197: newURL = newURL.replace(File.separatorChar, '/');
2198: if (newURL.startsWith("/")) {
2199: newURL = "file:" + newURL;
2200: } else {
2201: newURL = "file:/" + newURL;
2202: }
2203: assertEquals("Test 2: Incorrect URL Returned.", f.toURL()
2204: .toString(), newURL);
2205:
2206: // Regression test for HARMONY-3207
2207: dir = new File(""); // current directory
2208: newDirURL = dir.toURL().toString();
2209: assertTrue("Test current dir: URL does not end with slash.",
2210: newDirURL.endsWith("/"));
2211: }
2212:
2213: /**
2214: * @tests java.io.File#toURI()
2215: */
2216: public void test_toURI2() throws URISyntaxException {
2217: File f = new File(System.getProperty("user.dir"),
2218: "a/b/c/../d/e/./f");
2219:
2220: String path = f.getAbsolutePath();
2221: path = path.replace(File.separatorChar, '/');
2222: if (!path.startsWith("/")) {
2223: path = "/" + path;
2224: }
2225:
2226: URI uri1 = new URI("file", null, path, null);
2227: URI uri2 = f.toURI();
2228: assertEquals("uris not equal", uri1, uri2);
2229: }
2230:
2231: /**
2232: * @tests java.io.File#toURL()
2233: */
2234: public void test_toURL2() throws MalformedURLException {
2235: File f = new File(System.getProperty("user.dir"),
2236: "a/b/c/../d/e/./f");
2237:
2238: String path = f.getAbsolutePath();
2239: path = path.replace(File.separatorChar, '/');
2240: if (!path.startsWith("/")) {
2241: path = "/" + path;
2242: }
2243:
2244: URL url1 = new URL("file", "", path);
2245: URL url2 = f.toURL();
2246: assertEquals("urls not equal", url1, url2);
2247: }
2248:
2249: /**
2250: * @tests java.io.File#deleteOnExit()
2251: */
2252: public void test_deleteOnExit() throws IOException,
2253: InterruptedException {
2254: File dir = new File("dir4filetest");
2255: dir.mkdir();
2256: assertTrue(dir.exists());
2257: File subDir = new File("dir4filetest/subdir");
2258: subDir.mkdir();
2259: assertTrue(subDir.exists());
2260:
2261: Support_Exec.execJava(new String[] {
2262: "tests.support.Support_DeleteOnExitTest",
2263: dir.getAbsolutePath(), subDir.getAbsolutePath() },
2264: new String[] {}, false);
2265: assertFalse(dir.exists());
2266: assertFalse(subDir.exists());
2267: }
2268:
2269: /**
2270: * @tests serilization
2271: */
2272: public void test_objectStreamClass_getFields() throws Exception {
2273: // Regression for HARMONY-2674
2274: ObjectStreamClass objectStreamClass = ObjectStreamClass
2275: .lookup(File.class);
2276: ObjectStreamField[] objectStreamFields = objectStreamClass
2277: .getFields();
2278: assertEquals(1, objectStreamFields.length);
2279: ObjectStreamField objectStreamField = objectStreamFields[0];
2280: assertEquals("path", objectStreamField.getName());
2281: assertEquals(String.class, objectStreamField.getType());
2282: }
2283:
2284: // Regression test for HARMONY-4493
2285: public void test_list_withUnicodeFileName() throws Exception {
2286: File rootDir = new File("P");
2287: if (!rootDir.exists()) {
2288: rootDir.mkdir();
2289: rootDir.deleteOnExit();
2290: }
2291:
2292: String dirName = new String("src\u3400");
2293: File dir = new File(rootDir, dirName);
2294: if (!dir.exists()) {
2295: dir.mkdir();
2296: dir.deleteOnExit();
2297: }
2298: boolean exist = false;
2299: String[] fileNames = rootDir.list();
2300: for (String fileName : fileNames) {
2301: if (dirName.equals(fileName)) {
2302: exist = true;
2303: break;
2304: }
2305: }
2306: assertTrue(exist);
2307: }
2308:
2309: /**
2310: * @tests serialization/deserialization.
2311: */
2312: public void test_serialization_self() throws Exception {
2313: File testFile = new File("test.ser");
2314: SerializationTest.verifySelf(testFile);
2315: }
2316:
2317: /**
2318: * @tests serialization/deserialization compatibility with RI.
2319: */
2320: public void test_serialization_compatibility() throws Exception {
2321: File file = new File("FileTest.golden.ser");
2322: SerializationTest.verifyGolden(this , file);
2323: }
2324:
2325: /**
2326: * Sets up the fixture, for example, open a network connection. This method
2327: * is called before a test is executed.
2328: */
2329: protected void setUp() throws IOException {
2330: /** Setup the temporary directory */
2331: String userDir = System.getProperty("user.dir");
2332: if (userDir == null) {
2333: userDir = "j:\\jcl-builddir\\temp\\source";
2334: }
2335: if (!userDir.regionMatches((userDir.length() - 1), slash, 0, 1)) {
2336: userDir += slash;
2337: }
2338: tempDirectory = new File(userDir + "tempDir"
2339: + String.valueOf(System.currentTimeMillis()));
2340: if (!tempDirectory.mkdir()) {
2341: System.out.println("Setup for FileTest failed.");
2342: }
2343:
2344: /** Setup the temporary file */
2345: tempFile = new File(tempDirectory, "tempfile");
2346: FileOutputStream tempStream = new FileOutputStream(tempFile
2347: .getPath(), false);
2348: tempStream.close();
2349: }
2350:
2351: /**
2352: * Tears down the fixture, for example, close a network connection. This
2353: * method is called after a test is executed.
2354: */
2355: protected void tearDown() {
2356: tempFile.delete();
2357: tempDirectory.delete();
2358: }
2359: }
|