當前位置: 首頁>>代碼示例>>Java>>正文


Java File.getParentFile方法代碼示例

本文整理匯總了Java中java.io.File.getParentFile方法的典型用法代碼示例。如果您正苦於以下問題:Java File.getParentFile方法的具體用法?Java File.getParentFile怎麽用?Java File.getParentFile使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.io.File的用法示例。


在下文中一共展示了File.getParentFile方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: unzipDir

import java.io.File; //導入方法依賴的package包/類
public static boolean unzipDir(File in) throws Exception {
    totalFilesUnzip = 0;
    if (!in.exists()) {
        throw new IOException(in.getAbsolutePath() + " does not exist");
    }
    if (!buildDirectory(in.getParentFile())) {
        throw new IOException("Could not create directory: " + in.getParent());
    }
    try (ZipFile zipFile = new ZipFile(in)) {
        for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            File file = new File(in.getParent(), File.separator + entry.getName());
            if (!buildDirectory(file.getParentFile())) {
                throw new IOException("Could not create directory: " + file.getParentFile());
            }
            if (!entry.isDirectory()) {
                copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(file)));
                totalFilesUnzip++;
            } else if (!buildDirectory(file)) {
                throw new IOException("Could not create directory: " + file);
            }
        }
    }
    return true;
}
 
開發者ID:limagiran,項目名稱:hearthstone,代碼行數:26,代碼來源:Zip.java

示例2: checkName

import java.io.File; //導入方法依賴的package包/類
/**
 * Checks that the given entry name is legal for unzipping: if it contains
 * ".." as a name element, it could cause the entry to be unzipped outside
 * the directory we're unzipping to.
 *
 * @throws IOException if the name is illegal
 */
private static void checkName(String name) throws IOException {
  // First just check whether the entry name string contains "..".
  // This should weed out the the vast majority of entries, which will not
  // contain "..".
  if (name.contains("..")) {
    // If the string does contain "..", break it down into its actual name
    // elements to ensure it actually contains ".." as a name, not just a
    // name like "foo..bar" or even "foo..", which should be fine.
    File file = new File(name);
    while (file != null) {
      if (file.getName().equals("..")) {
        throw new IOException("Cannot unzip file containing an entry with "
            + "\"..\" in the name: " + name);
      }
      file = file.getParentFile();
    }
  }
}
 
開發者ID:spotify,項目名稱:hype,代碼行數:26,代碼來源:ZipFiles.java

示例3: saveDonateQrImage2SDCard

import java.io.File; //導入方法依賴的package包/類
/**
 * 保存圖片到本地,需要權限
 * @param qrBitmap 二維碼圖片
 */
public static void saveDonateQrImage2SDCard(@NonNull String qrSavePath, @NonNull Bitmap qrBitmap) {
    File qrFile = new File(qrSavePath);
    File parentFile = qrFile.getParentFile();
    if (!parentFile.exists()) {
        parentFile.mkdirs();
    }
    try {
        FileOutputStream fos = new FileOutputStream(qrFile);
        qrBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
開發者ID:gtf35,項目名稱:easyShopping,代碼行數:20,代碼來源:WeiXinDonate.java

示例4: upZipFile

import java.io.File; //導入方法依賴的package包/類
/**
  * 解壓縮一個文件
  *
  * @param zipFile 壓縮文件
  * @param folderPath 解壓縮的目標目錄
  * @throws IOException 當解壓縮過程出錯時拋出
  */
 public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException {
     File desDir = new File(folderPath);
     if (!desDir.exists()) {
         desDir.mkdirs();
     }
     ZipFile zf = new ZipFile(zipFile);
     for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
         ZipEntry entry = ((ZipEntry)entries.nextElement());
         if (entry.isDirectory()) {
	
         	continue;
}
         InputStream in = zf.getInputStream(entry);
         String str = folderPath + File.separator + entry.getName();
         str = new String(str.getBytes(), "utf-8");
         File desFile = new File(str);
         if (!desFile.exists()) {
             File fileParentDir = desFile.getParentFile();
             if (!fileParentDir.exists()) {
                 fileParentDir.mkdirs();
             }
             desFile.createNewFile();
         }
         OutputStream out = new FileOutputStream(desFile);
         byte buffer[] = new byte[BUFF_SIZE];
         int realLength;
         while ((realLength = in.read(buffer)) > 0) {
             out.write(buffer, 0, realLength);
         }
         in.close();
         out.close();
     }
 }
 
開發者ID:BaoBaoJianqiang,項目名稱:HybridForAndroid,代碼行數:41,代碼來源:ZipUtils.java

示例5: deleteFile

import java.io.File; //導入方法依賴的package包/類
private void deleteFile (File file, File[] roots) {
    Set<File> rootFiles = new HashSet<File>(Arrays.asList(roots));
    File[] children;
    while (file != null && !rootFiles.contains(file) && ((children = file.listFiles()) == null || children.length == 0)) {
        // file is an empty folder
        if (!file.delete()) {
            monitor.notifyWarning("Cannot delete " + file.getAbsolutePath());
        }
        file = file.getParentFile();
    }
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:12,代碼來源:ResetCommand.java

示例6: testNewChildNoticed

import java.io.File; //導入方法依賴的package包/類
public void testNewChildNoticed() throws Exception {
    FileObject fileObject1 = testFolder.createData("fileObject1");
    FileObject[] arr = testFolder.getChildren();
    assertEquals("One child", 1, arr.length);
    assertEquals("Right child", fileObject1, arr[0]);

    File file = FileUtil.toFile(fileObject1);
    assertNotNull("File found", file);
    arr = null;
    fileObject1 = null;
    Reference<FileObject> ref = new WeakReference<FileObject>(fileObject1);
    assertGC("File Object can disappear", ref);

    Thread.sleep(100);

    class L extends FileChangeAdapter {
        int cnt;
        FileEvent event;

        @Override
        public void fileDataCreated(FileEvent fe) {
            cnt++;
            event = fe;
        }

    }
    L listener = new L();
    testFolder.addRecursiveListener(listener);

    File nfile = new File(file.getParentFile(), "new.txt");
    nfile.createNewFile();

    testFolder.refresh();

    assertEquals("Change notified", 1, listener.cnt);
    assertEquals("Right file", nfile, FileUtil.toFile(listener.event.getFile()));
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:38,代碼來源:ExternalTouchTest.java

示例7: getAudioSavePath

import java.io.File; //導入方法依賴的package包/類
public static String getAudioSavePath(long userId) {
    String path = getSavePath(SysConstant.FILE_SAVE_TYPE_AUDIO) + userId
            + "_" + String.valueOf(System.currentTimeMillis())
            + ".spx";
    File file = new File(path);
    File parent = file.getParentFile();
    if (parent != null && !parent.exists()) {
        parent.mkdirs();
    }
    return path;
}
 
開發者ID:ccfish86,項目名稱:sctalk,代碼行數:12,代碼來源:CommonUtil.java

示例8: testNewChildNoticed

import java.io.File; //導入方法依賴的package包/類
public void testNewChildNoticed() throws Exception {
    FileObject fileObject1 = testFolder.createData("fileObject1");
    FileObject[] arr = testFolder.getChildren();
    assertEquals("One child", 1, arr.length);
    assertEquals("Right child", fileObject1, arr[0]);

    File file = FileUtil.toFile(fileObject1);
    assertNotNull("File found", file);
    arr = null;
    fileObject1 = null;
    Reference<FileObject> ref = new WeakReference<FileObject>(fileObject1);
    assertGC("File Object can disappear", ref);

    class L extends FileChangeAdapter {
        int cnt;
        FileEvent event;

        @Override
        public void fileDataCreated(FileEvent fe) {
            cnt++;
            event = fe;
        }

    }
    L listener = new L();
    testFolder.addRecursiveListener(listener);

    File nfile = new File(file.getParentFile(), "new.txt");
    nfile.createNewFile();
    TestFileUtils.touch(nfile, null);

    testFolder.refresh();

    assertEquals("Change notified", 1, listener.cnt);
    assertEquals("Right file", nfile, FileUtil.toFile(listener.event.getFile()));
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:37,代碼來源:LocalFileSystemExternalTouchTest.java

示例9: getFilePath

import java.io.File; //導入方法依賴的package包/類
private String getFilePath(NexusScanInfo info) {
	final File scanFile = new File(info.getFilePath());
	final File scanDir = scanFile.getParentFile();
	String scanFileNameNoExtn = scanFile.getName();
	final int dotIndex = scanFileNameNoExtn.indexOf('.');
	if (dotIndex != -1) {
		scanFileNameNoExtn = scanFileNameNoExtn.substring(0, dotIndex);
	}
	final File outputDir = new File(scanDir, scanFileNameNoExtn);
	outputDir.mkdir();

	final String filePath = new File(outputDir, "posdetector.h5").getAbsolutePath();
	return filePath;
}
 
開發者ID:eclipse,項目名稱:scanning,代碼行數:15,代碼來源:PosDetector.java

示例10: valid

import java.io.File; //導入方法依賴的package包/類
private static State valid(File file) {
	File parentPath = file.getParentFile();

	if ((!parentPath.exists()) && (!parentPath.mkdirs())) {
		return new BaseState(false, 3);
	}

	if (!parentPath.canWrite()) {
		return new BaseState(false, 2);
	}

	return new BaseState(true);
}
 
開發者ID:daima,項目名稱:solo-spring,代碼行數:14,代碼來源:StorageManager.java

示例11: ensureParentFolderExists

import java.io.File; //導入方法依賴的package包/類
private boolean ensureParentFolderExists (File parentFolder) {
    File predecessor = parentFolder;
    while (!predecessor.exists()) {
        predecessor = predecessor.getParentFile();
    }
    if (predecessor.isFile()) {
        if (!predecessor.delete()) {
            monitor.notifyError(MessageFormat.format(Utils.getBundle(CheckoutIndex.class).getString("MSG_Warning_CannotCreateFile"), predecessor.getAbsolutePath())); //NOI18N
            return false;
        }
        monitor.notifyWarning(MessageFormat.format(Utils.getBundle(CheckoutIndex.class).getString("MSG_Warning_ReplacingFile"), predecessor.getAbsolutePath())); //NOI18N
    }
    return parentFolder.mkdirs() || parentFolder.exists();
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:15,代碼來源:CheckoutIndex.java

示例12: SqlFile

import java.io.File; //導入方法依賴的package包/類
/**
 * Wrapper for SqlFile(SqlFile, Reader, String)
 *
 * @see #SqlFile(SqlFile, Reader, String)
 */
private SqlFile(SqlFile parentSqlFile, File inputFile) throws IOException {
    this(parentSqlFile,
            new InputStreamReader(new FileInputStream(inputFile),
            (parentSqlFile.shared.encoding == null)
            ? DEFAULT_FILE_ENCODING : parentSqlFile.shared.encoding),
            inputFile.toString(), inputFile.getParentFile());
}
 
開發者ID:tiweGH,項目名稱:OpenDiabetes,代碼行數:13,代碼來源:SqlFile.java

示例13: deleteDatabase

import java.io.File; //導入方法依賴的package包/類
/**
 * Deletes a database including its journal file and other auxiliary files
 * that may have been created by the database engine.
 *
 * @param file The database file path.
 * @return True if the database was successfully deleted.
 */
public static boolean deleteDatabase(File file) {
    if (file == null) {
        throw new IllegalArgumentException("file must not be null");
    }

    boolean deleted = false;
    deleted |= file.delete();
    deleted |= new File(file.getPath() + "-journal").delete();
    deleted |= new File(file.getPath() + "-shm").delete();
    deleted |= new File(file.getPath() + "-wal").delete();

    File dir = file.getParentFile();
    if (dir != null) {
        final String prefix = file.getName() + "-mj";
        File[] files = dir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File candidate) {
                return candidate.getName().startsWith(prefix);
            }
        });
        if (files != null) {
            for (File masterJournal : files) {
                deleted |= masterJournal.delete();
            }
        }
    }
    return deleted;
}
 
開發者ID:kkmike999,項目名稱:YuiHatano,代碼行數:36,代碼來源:ShadowSQLiteDatabase.java

示例14: doGenerateOSOnlySimpleModule

import java.io.File; //導入方法依賴的package包/類
private void doGenerateOSOnlySimpleModule(String tok, String find) throws Exception {
    Manifest m;
    
    m = createManifest ();
    m.getMainAttributes ().putValue ("OpenIDE-Module", "org.my.module/3");
    m.getMainAttributes ().putValue ("OpenIDE-Module-Requires", tok + ", pepa.z.bota");
    File simpleJar = generateJar (new String[0], m);

    File parent = simpleJar.getParentFile ();
    File output = new File(parent, "output");
    File ks = generateKeystore("jnlp", "netbeans-test");
    
    java.io.File f = extractString (
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
        "<project name=\"Test Arch\" basedir=\".\" default=\"all\" >" +
        "  <taskdef name=\"jnlp\" classname=\"org.netbeans.nbbuild.MakeJNLP\" classpath=\"${nbantext.jar}\"/>" +
        "<target name=\"all\" >" +
        "  <mkdir dir='" + output + "' />" + 
        "  <jnlp dir='" + output + "' alias='jnlp' storepass='netbeans-test' keystore='" + ks + "' signjars='false' >" +
        "    <modules dir='" + parent + "' >" +
        "      <include name='" + simpleJar.getName() + "' />" +
        "    </modules>" +
        "  </jnlp>" +
        "</target>" +
        "</project>"
    );
    execute (f, new String[] { "-verbose" });
    
    assertFilenames(output, "org-my-module.jnlp", "org-my-module/s0.jar");
    
    File jnlp = new File(output, "org-my-module.jnlp");
    String res = readFile (jnlp);
    
    assertTrue ("Component JNLP type: " + res, res.indexOf ("<component-desc/>") >= 0);
    assertTrue ("Resource is os dependant: " + res, res.indexOf (find) >= 0);
    assertTrue ("We support all permissions by default: " + res, res.indexOf ("<all-permissions/>") >= 0);
    
    Matcher match = Pattern.compile(".*codebase=['\\\"]([^'\\\"]*)['\\\"]").matcher(res);
    assertTrue("codebase is there", match.find());
    assertEquals("one group found", 1, match.groupCount());
    String base = match.group(1);
    
    assertEquals("By default the dest directory is $$codebase: ", "$$codebase", base);

    File jar = new File(output, "org-my-module/s0.jar");
    JarFile signed = new JarFile(jar);
    Enumeration<JarEntry> it = signed.entries();
    while (it.hasMoreElements()) {
        JarEntry entry = it.nextElement();
        if (entry.getName().endsWith(".SF")) {
            fail ("File should not be signed: " + jar);
        }
    }
    
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:56,代碼來源:MakeJNLPTest.java

示例15: addItem

import java.io.File; //導入方法依賴的package包/類
/**
 * Adds the directory to the model and sets it to be selected,
 * additionally clears out the previous selected directory and
 * the paths leading up to it, if any.
 */
private void addItem(File directory) {

    if(directory == null) {
        return;
    }

    boolean useShellFolder = FilePane.usesShellFolder(chooser);

    directories.clear();

    File[] baseFolders = (useShellFolder)
            ? (File[]) ShellFolder.get("fileChooserComboBoxFolders")
            : fsv.getRoots();
    directories.addAll(Arrays.asList(baseFolders));

    // Get the canonical (full) path. This has the side
    // benefit of removing extraneous chars from the path,
    // for example /foo/bar/ becomes /foo/bar
    File canonical;
    try {
        canonical = directory.getCanonicalFile();
    } catch (IOException e) {
        // Maybe drive is not ready. Can't abort here.
        canonical = directory;
    }

    // create File instances of each directory leading up to the top
    try {
        File sf = useShellFolder ? ShellFolder.getShellFolder(canonical)
                                 : canonical;
        File f = sf;
        Vector<File> path = new Vector<File>(10);
        do {
            path.addElement(f);
        } while ((f = f.getParentFile()) != null);

        int pathCount = path.size();
        // Insert chain at appropriate place in vector
        for (int i = 0; i < pathCount; i++) {
            f = path.get(i);
            if (directories.contains(f)) {
                int topIndex = directories.indexOf(f);
                for (int j = i-1; j >= 0; j--) {
                    directories.insertElementAt(path.get(j), topIndex+i-j);
                }
                break;
            }
        }
        calculateDepths();
        setSelectedItem(sf);
    } catch (FileNotFoundException ex) {
        calculateDepths();
    }
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:60,代碼來源:WindowsFileChooserUI.java


注:本文中的java.io.File.getParentFile方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。