Java Code Examples for java.io.File.getParentFile()

The following are Jave code examples for showing how to use getParentFile() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: hearthstone   File: Zip.java   View Source Code Vote up 6 votes
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;
}
 
Example 2
Project: hype   File: ZipFiles.java   View Source Code Vote up 6 votes
/**
 * 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();
    }
  }
}
 
Example 3
Project: easyShopping   File: WeiXinDonate.java   View Source Code Vote up 6 votes
/**
 * 保存图片到本地,需要权限
 * @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();
    }
}
 
Example 4
Project: HybridForAndroid   File: ZipUtils.java   View Source Code Vote up 5 votes
/**
  * 解压缩一个文件
  *
  * @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();
     }
 }
 
Example 5
Project: incubator-netbeans   File: ResetCommand.java   View Source Code Vote up 5 votes
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();
    }
}
 
Example 6
Project: incubator-netbeans   File: ExternalTouchTest.java   View Source Code Vote up 5 votes
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()));
}
 
Example 7
Project: sctalk   File: CommonUtil.java   View Source Code Vote up 5 votes
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;
}
 
Example 8
Project: incubator-netbeans   File: LocalFileSystemExternalTouchTest.java   View Source Code Vote up 5 votes
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()));
}
 
Example 9
Project: scanning   File: PosDetector.java   View Source Code Vote up 5 votes
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;
}
 
Example 10
Project: solo-spring   File: StorageManager.java   View Source Code Vote up 5 votes
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);
}
 
Example 11
Project: incubator-netbeans   File: CheckoutIndex.java   View Source Code Vote up 5 votes
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();
}
 
Example 12
Project: OpenDiabetes   File: SqlFile.java   View Source Code Vote up 5 votes
/**
 * 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());
}
 
Example 13
Project: YuiHatano   File: ShadowSQLiteDatabase.java   View Source Code Vote up 5 votes
/**
 * 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;
}
 
Example 14
Project: incubator-netbeans   File: MakeJNLPTest.java   View Source Code Vote up 4 votes
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);
        }
    }
    
}
 
Example 15
Project: OpenJSharp   File: WindowsFileChooserUI.java   View Source Code Vote up 4 votes
/**
 * 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();
    }
}
 
Example 16
Project: atlas   File: AtlasProguardTransform.java   View Source Code Vote up 4 votes
private void doMainBundleProguard(TransformInvocation invocation) throws Exception {

        //apply bundle Inout
        Profiler.enter("bundleKeep");
        File bundleKeep = AtlasProguardHelper.generateBundleKeepCfg(appVariantContext);
        Profiler.release();

        Input input = new Input();
        AwbBundle awbBundle = new AwbBundle();
        awbBundle.getAndroidLibraries().addAll(AtlasBuildContext.androidDependencyTrees.get(appVariantContext.getVariantName()).getMainBundle().getAndroidLibraries());
        AwbTransform awbTransform = new AwbTransform(awbBundle);
        input.getAwbBundles().add(awbTransform);

        List<File> unProguardJars = new ArrayList<>();
        //Enter the input
        for (TransformInput transformInput : invocation.getInputs()) {
            for (JarInput jarInput : transformInput.getJarInputs()) {
                File file = jarInput.getFile();
                if (file.getName().startsWith("combined-rmerge")) {
                    unProguardJars.add(file);
                } else {
                    awbTransform.getInputLibraries().add(file);
                }
            }
            for (DirectoryInput directoryInput : transformInput.getDirectoryInputs()) {
                awbTransform.getInputLibraries().add(directoryInput.getFile());
            }
        }

        //inputting librarys
        input.getLibraries().addAll(
            appVariantContext.getScope().getGlobalScope().getAndroidBuilder().getBootClasspath(true));
        input.getLibraries().addAll(unProguardJars);

        //The default proguard configuration
        input.getDefaultProguardFiles().addAll(defaultProguardFiles);

        //bundle keeps
        input.getParentKeeps().add(bundleKeep);

        File outFile = invocation.getOutputProvider().getContentLocation("main", getOutputTypes(), getScopes(),
                                                                         Format.JAR);
        outFile.delete();
        input.proguardOutputDir = outFile.getParentFile();
        input.printMapping = (File)ReflectUtils.getField(oldTransform, "printMapping");
        input.dump = (File)ReflectUtils.getField(oldTransform, "dump");
        input.printSeeds = (File)ReflectUtils.getField(oldTransform, "printSeeds");
        input.printUsage = (File)ReflectUtils.getField(oldTransform, "printUsage");
        input.printConfiguration = new File(appVariantContext.getProject().getBuildDir(), "outputs/proguard.cfg");

        Profiler.enter("executeproguard");
        BundleProguarder.execute(appVariantContext, input);
        Profiler.release();

        for (File jar : unProguardJars) {

            File to = invocation.getOutputProvider().getContentLocation(FileNameUtils.getUniqueJarName(jar),
                                                                        getOutputTypes(), getScopes(),
                                                                        Format.JAR);
            FileUtils.copyFile(jar, to);

        }

    }
 
Example 17
Project: hdr-histogram-plotter   File: HdrPropertyWriter.java   View Source Code Vote up 4 votes
/**
 * Save a summary of the analyzed rate data to a properties file named "rate.properties"
 * @param histogramFile the directory where the saved file will be located
 * @throws IOException if unable to save
 */
public static void writeFrom(final String histogramFile) throws IOException {
    File in = new File(histogramFile);
    logger.trace("Writing properties to {}/latency.properties", in.getPath());

    Properties prop = new Properties();

    HistogramLogReader histogramLogReader = new HistogramLogReader(in);

    EncodableHistogram eh = histogramLogReader.nextIntervalHistogram();

    prop.setProperty("latencyStartTS", Long.toString(eh.getStartTimeStamp()));
    prop.setProperty("latencyEndTS", Long.toString(eh.getEndTimeStamp()));

    prop.setProperty("latencyMaxValue", Double.toString(eh.getMaxValueAsDouble()));


    if (eh instanceof AbstractHistogram) {
        AbstractHistogram ah = (AbstractHistogram) eh;

        prop.setProperty("latency50th", Long.toString(ah.getValueAtPercentile(50.0)));
        prop.setProperty("latency90th", Long.toString(ah.getValueAtPercentile(90.0)));
        prop.setProperty("latency95th", Long.toString(ah.getValueAtPercentile(95.0)));
        prop.setProperty("latency99th", Long.toString(ah.getValueAtPercentile(99.0)));
        prop.setProperty("latency999th", Long.toString(ah.getValueAtPercentile(99.9)));
        prop.setProperty("latency9999th", Long.toString(ah.getValueAtPercentile(99.99)));
        prop.setProperty("latencyStdDeviation", Double.toString(ah.getStdDeviation()));
        prop.setProperty("latencyTotalCount", Long.toString(ah.getTotalCount()));
        prop.setProperty("latencyMean", Double.toString(ah.getMean()));
    }
    else {
        if (eh instanceof DoubleHistogram) {
            DoubleHistogram dh = (DoubleHistogram) eh;

            prop.setProperty("latency50th", Double.toString(dh.getValueAtPercentile(50.0)));
            prop.setProperty("latency90th", Double.toString(dh.getValueAtPercentile(90.0)));
            prop.setProperty("latency95th", Double.toString(dh.getValueAtPercentile(95.0)));
            prop.setProperty("latency99th", Double.toString(dh.getValueAtPercentile(99.0)));
            prop.setProperty("latency999th", Double.toString(dh.getValueAtPercentile(99.9)));
            prop.setProperty("latency9999th", Double.toString(dh.getValueAtPercentile(99.99)));
            prop.setProperty("latencyStdDeviation", Double.toString(dh.getStdDeviation()));
            prop.setProperty("latencyTotalCount", Long.toString(dh.getTotalCount()));
            prop.setProperty("latencyMean", Double.toString(dh.getMean()));
        }
    }


    try (FileOutputStream fos = new FileOutputStream(new File(in.getParentFile(), "latency.properties"))) {
        prop.store(fos, "hdr-histogram-plotter");
    }
}
 
Example 18
Project: incubator-netbeans   File: ModuleDependenciesTest.java   View Source Code Vote up 4 votes
public void testGenerateModuleDependencies () throws Exception {
    Manifest openideManifest = createManifest ();
    openideManifest.getMainAttributes ().putValue ("OpenIDE-Module", "org.openide/1");
    File openide = generateJar (new String[] { "notneeded" }, openideManifest);
    
    Manifest m = createManifest ();
    m.getMainAttributes ().putValue ("OpenIDE-Module", "my.module/3");
    m.getMainAttributes ().putValue ("OpenIDE-Module-Module-Dependencies", "org.openide/1 > 4.17");
    File withoutPkgs = generateJar (new String[] { "notneeded" }, m);
    
    m = createManifest ();
    m.getMainAttributes ().putValue ("OpenIDE-Module", "my.another.module/3");
    m.getMainAttributes ().putValue ("OpenIDE-Module-Module-Dependencies", "my.module/3, org.openide/1 > 4.17");
    File withPkgs = generateJar (new String[] { "some content"}, m);
    
    File parent = openide.getParentFile ();
    assertEquals ("All parents are the same 1", parent, withoutPkgs.getParentFile ());
    assertEquals ("All parents are the same 2", parent, withPkgs.getParentFile ());
    
    
    File output = extractString ("");
    output.delete ();
    assertFalse ("Is gone", output.exists ());
    java.io.File f = extractString (
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
        "<project name=\"Test Arch\" basedir=\".\" default=\"all\" >" +
        "  <taskdef name=\"deps\" classname=\"org.netbeans.nbbuild.ModuleDependencies\" classpath=\"${nbantext.jar}\"/>" +
        "<target name=\"all\" >" +
        "  <deps>" +
        "    <input name=\"platform\" >" +
        "      <jars dir=\"" + parent + "\" > " +
        "        <include name=\"" + openide.getName () + "\" />" +
        "      </jars>" +
        "    </input>" +
        "    <input name=\"ahoj\" >" +
        "      <jars dir=\"" + parent + "\" > " +
        "        <include name=\"" + withoutPkgs.getName () + "\" />" +
        "        <include name=\"" + withPkgs.getName () + "\" />" +
        "      </jars>" +
        "    </input>" +
        "    <output type=\"dependencies\" file=\"" + output + "\" />" +
        "  </deps >" +
        "</target>" +
        "</project>"
    );
    execute (f, new String[] { "-verbose" });
    
    assertTrue ("Result generated", output.exists ());
    
    String res = readFile (output);
    int y = res.indexOf ("MODULE", 1);
    if (y <= 0) {
        fail ("There is another module: " + y + " res: " + res);
    }
    assertEquals ("No other", -1, res.indexOf ("MODULE", y + 1));

    // f1 is later due to algebraic sorting of modules!!!!
    StringTokenizer f2 = new StringTokenizer (res.substring (0, y), "\r\n");
    StringTokenizer f1 = new StringTokenizer (res.substring (y), "\r\n");
    
    assertEquals ("One line + one dep for f1\n" + res, 2, f1.countTokens ());
    f1.nextToken ();
    String dep1 = f1.nextToken ();
    assertTrue (dep1, dep1.startsWith ("  REQUIRES"));
    assertTrue ("on " + dep1, dep1.indexOf ("org.openide") >= 0);
    
    assertEquals ("One line + two dep for f2", 3, f2.countTokens ());
    f2.nextToken ();
    String dep2 = f2.nextToken ();
    assertTrue (dep2, dep2.startsWith ("  REQUIRES"));
    assertTrue ("on my " + dep2, dep2.indexOf ("my.module") >= 0);
    dep2 = f2.nextToken ();
    assertTrue (dep2, dep2.startsWith ("  REQUIRES"));
    assertTrue ("on " + dep2, dep2.indexOf ("org.openide") >= 0);
    
}
 
Example 19
Project: dswork   File: FileUtil.java   View Source Code Vote up 4 votes
/**
 * 复制
 * @param fromFilePath 源文件或文件夹路径(全路径)
 * @param toFilePath 目标文件或文件夹路径(全路径)
 * @param overwrite 复制过程中遇到已存在的文件夹或文件是否覆盖改写
 * @param copySubdir 复制文件夹时,是否复制子文件夹
 */
public static void copy(String fromFilePath, String toFilePath, boolean overwrite, boolean copySubdir)
{
	File from = new File(fromFilePath);
	File to = new File(toFilePath);
	try
	{
		if(!from.exists())// 不存在来源(不是文件,也不是文件夹)
		{
			return;
		}
		if(to.exists() && !overwrite)// 当目标已存在,并且不能覆盖时
		{
			return;
		}
		if(from.isDirectory())
		{
			if(to.isFile())// 当目标已存在,保留文件夹,删除文件
			{
				FileUtil.delete(toFilePath);// 删除文件,让它变成文件夹
			}
			to.mkdirs();
			if(!to.exists())// 上面某一级是文件的情况,否则肯定创建成功
			{
				int i = 100;// 防止死循环
				File s = to.getParentFile();
				while(!s.exists() && i > 0)
				{
					s = s.getParentFile();
					i--;
				}
				if(s.isFile())// 找到那个文件了
				{
					delete(s.getPath());// 干掉它
					to.mkdirs();// 重新创建目录结构
				}
			}
			String[] fileList = from.list();
			if(fileList == null)
			{
				return;
			}
			for(int i = 0; i < fileList.length; i++)
			{
				File f = new File(from.getAbsoluteFile() + "/" + fileList[i]);
				if(f.isDirectory() && !copySubdir)
				{
					continue;// 不复制子文件夹
				}
				copy(f.getPath(), to.getAbsoluteFile() + "/" + fileList[i], overwrite, copySubdir);
			}
		}
		else if(from.isFile())
		{
			File parentFile = to.getParentFile();
			if(!parentFile.exists())
			{
				parentFile.mkdirs();// 创建所属目录
			}
			if(to.exists())// 当目标已存在,删除文件或文件夹
			{
				FileUtil.delete(toFilePath);// 递归删除文件或子文件夹,让它变成文件
			}
			writeFile(to.getPath(), (new FileInputStream(from)), true);
		}
	}
	catch(Exception e)
	{
		e.printStackTrace();
	}
}
 
Example 20
Project: karate   File: ScriptEnv.java   View Source Code Vote up 4 votes
public static ScriptEnv init(String env, File featureFile, String[] searchPaths, Logger logger) {
    return new ScriptEnv(env, featureFile.getParentFile(), featureFile.getName(), 
            FileUtils.createClassLoader(searchPaths), new CallCache(), logger, null, new Debug());
}