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

The following are Jave code examples for showing how to use getCanonicalPath() 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: incubator-netbeans   File: ProfilerEngineSettings.java   View Source Code Vote up 7 votes
public void initialize(String rootDirName) throws RuntimeException, IOException {
    String jFluidNativeLibFullName = Platform.getAgentNativeLibFullName(rootDirName, false, null, -1);

    String jFluidNativeLibDirName = jFluidNativeLibFullName.substring(0, jFluidNativeLibFullName.lastIndexOf('/')); // NOI18N

    String checkedPath = ""; // NOI18N   // Needed only for error reporting

    try {
        File rootDir = MiscUtils.checkDirForName(checkedPath = rootDirName);
        MiscUtils.checkDirForName(checkedPath = jFluidNativeLibDirName);
        MiscUtils.checkFile(new File(checkedPath = jFluidNativeLibFullName), false);

        jFluidRootDirName = rootDir.getCanonicalPath();
    } catch (IOException e) {
        throw new IOException("Problem with a required JFluid installation directory or file " + checkedPath, e);
    }
}
 
Example 2
Project: Logisim   File: OpenRecent.java   View Source Code Vote up 6 votes
private static String getFileText(File file) {
	if (file == null) {
		return Strings.get("fileOpenRecentNoChoices");
	} else {
		String ret;
		try {
			ret = file.getCanonicalPath();
		} catch (IOException e) {
			ret = file.toString();
		}
		if (ret.length() <= MAX_ITEM_LENGTH) {
			return ret;
		} else {
			ret = ret.substring(ret.length() - MAX_ITEM_LENGTH + 3);
			int splitLoc = ret.indexOf(File.separatorChar);
			if (splitLoc >= 0) {
				ret = ret.substring(splitLoc);
			}
			return "..." + ret;
		}
	}
}
 
Example 3
Project: openaudible   File: ResourceList.java   View Source Code Vote up 6 votes
private static Collection<String> getResourcesFromDirectory(
        final File directory,
        final Pattern pattern) {
    final ArrayList<String> retval = new ArrayList<>();
    final File[] fileList = directory.listFiles();
    for (final File file : fileList) {
        if (file.isDirectory()) {
            retval.addAll(getResourcesFromDirectory(file, pattern));
        } else {
            try {
                final String fileName = file.getCanonicalPath();
                final boolean accept = pattern.matcher(fileName).matches();
                if (accept) {
                    retval.add(fileName);
                }
            } catch (final IOException e) {
                throw new Error(e);
            }
        }
    }
    return retval;
}
 
Example 4
Project: openNaEF   File: DumpCommand.java   View Source Code Vote up 6 votes
@Override public void process(Commandline args) throws ShellCommandException {
    checkArgsSize(args, 0);

    beginReadTransaction();

    try {
        File outDir = new File(".", "dump");
        if (! outDir.exists()) {
            outDir.mkdir();
        } else if (! outDir.isDirectory()) {
            throw new ShellCommandException("出力先エラー: " + outDir.getCanonicalPath());
        }

        for (UiTypeName typename : SkeltonTefService.instance().uiTypeNames().instances()) {
            dump(outDir, typename);
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}
 
Example 5
Project: mumu   File: DataUtil.java   View Source Code Vote up 6 votes
/**
 * 这个方法可以通过与某个类的class文件的相对路径来获取文件或目录的绝对路径。 通常在程序中很难定位某个相对路径,特别是在B/S应用中。
 * 通过这个方法,我们可以根据我们程序自身的类文件的位置来定位某个相对路径。
 * 比如:某个txt文件相对于程序的Test类文件的路径是../../resource/test.txt,
 * 那么使用本方法Path.getFullPathRelateClass("../../resource/test.txt",Test.class)
 * 得到的结果是txt文件的在系统中的绝对路径。
 * 
 * @param relatedPath 相对路径
 * @param cls 用来定位的类
 * @return 相对路径所对应的绝对路径
 * @throws IOException 因为本方法将查询文件系统,所以可能抛出IO异常
 */
public static final String getFullPathRelateClass(String relatedPath, Class<?> cls) {
	String path = null;
	if (relatedPath == null) {
		throw new NullPointerException();
	}
	String clsPath = getPathFromClass(cls);
	File clsFile = new File(clsPath);
	String tempPath = clsFile.getParent() + File.separator + relatedPath;
	File file = new File(tempPath);
	try {
		path = file.getCanonicalPath();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return path;
}
 
Example 6
Project: fort_j   File: Files.java   View Source Code Vote up 6 votes
@ApiMethod
public static boolean copy(File srcDir, File srcFile, File dstDir)
{
   try
   {
      String dest = srcFile.getCanonicalPath();
      dest = dest.substring(srcDir.getCanonicalPath().length(), dest.length());
      if (dest.startsWith("/") || dest.startsWith("\\"))
      {
         dest = dest.substring(1, dest.length());
      }

      File dstFile = new File(dstDir, dest);
      return copyFile(srcFile, dstFile);
   }
   catch (Exception ex)
   {
      Lang.rethrow(ex);
   }
   return false;
}
 
Example 7
Project: OpenDA   File: SwanVisualizer.java   View Source Code Vote up 6 votes
public void produceAdditionalOutput() {
    File swanVisualizerExe = visualizerConfig.getVisualizerExe();
    File swivtPresentationSettingsFile = visualizerConfig.getPresentationSettingsDirectory();
    File outputDir = visualizerConfig.getOutputDirectory();
    System.out.println("SWIVT OUT:\n\t" + swanVisualizerExe.getAbsolutePath() + "\n\t" +
            swivtPresentationSettingsFile.getAbsolutePath() + "\n\t" +
            outputDir.getAbsolutePath());
    try {
        String dirSep = File.separator;
        String[] arguments = new String[]{
                swanVisualizerExe.getParentFile().getCanonicalPath() + dirSep,
                swivtPresentationSettingsFile.getCanonicalPath() + dirSep,   // TODO:  + dirSep for Swivt 2.0
                visualizerConfig.getObservationDirectory().getCanonicalPath() + dirSep,
                visualizerConfig.getModelDirectory().getCanonicalPath() + dirSep,
                visualizerConfig.getOutputDirectory().getCanonicalPath() + dirSep
        };
        BBUtils.runExecutable(swanVisualizerExe.getAbsolutePath(), swanVisualizerExe.getParentFile(), arguments);
    } catch (IOException e) {
        throw new RuntimeException("Could not run " + swanVisualizerExe.getAbsolutePath());
    }
}
 
Example 8
Project: oscm-app   File: InitializerTest.java   View Source Code Vote up 6 votes
@Test
public void testLoggingWrongFileType() throws Exception {
    File log4jFile = createLog4jFile(LOG4J_CONFIG1);
    try {
        // Set path of log4j properties
        String log4jPath = log4jFile.getCanonicalPath();
        setSysSetting(log4jPath);

        // Invoke "private" method :)
        Method method = testElm.getClass().getDeclaredMethod(
                "postConstruct");
        method.setAccessible(true);
        method.invoke(testElm);

    } finally {
        log4jFile.delete();
        resetSysSetting();
    }

}
 
Example 9
Project: tomcat7   File: HostConfig.java   View Source Code Vote up 5 votes
private boolean validateContextPath(File appBase, String contextPath) {
    // More complicated than the ideal as the canonical path may or may
    // not end with File.separator for a directory

    StringBuilder docBase;
    String canonicalDocBase = null;

    try {
        String canonicalAppBase = appBase.getCanonicalPath();
        docBase = new StringBuilder(canonicalAppBase);
        if (canonicalAppBase.endsWith(File.separator)) {
            docBase.append(contextPath.substring(1).replace(
                    '/', File.separatorChar));
        } else {
            docBase.append(contextPath.replace('/', File.separatorChar));
        }
        // At this point docBase should be canonical but will not end
        // with File.separator

        canonicalDocBase =
            (new File(docBase.toString())).getCanonicalPath();

        // If the canonicalDocBase ends with File.separator, add one to
        // docBase before they are compared
        if (canonicalDocBase.endsWith(File.separator)) {
            docBase.append(File.separator);
        }
    } catch (IOException ioe) {
        return false;
    }

    // Compare the two. If they are not the same, the contextPath must
    // have /../ like sequences in it
    return canonicalDocBase.equals(docBase.toString());
}
 
Example 10
Project: hadoop   File: HardLink.java   View Source Code Vote up 5 votes
@Override
String[] linkCount(File file) throws IOException {
  String[] buf = new String[getLinkCountCommand.length];
  System.arraycopy(getLinkCountCommand, 0, buf, 0, 
                   getLinkCountCommand.length);
  buf[getLinkCountCommand.length - 1] = file.getCanonicalPath();
  return buf;
}
 
Example 11
Project: GitHub   File: MatchPatternsFileFilter.java   View Source Code Vote up 5 votes
String relativePath(File file) throws IOException {
    String canonicalPath = file.getCanonicalPath();
    if (!canonicalPath.startsWith(sourceDirectory)) {
        throw new IOException(format("the path %s is not a decendent of the basedir %s", canonicalPath, sourceDirectory));
    }
    return canonicalPath.substring(sourceDirectory.length()).replaceAll("^" + quote(File.separator), "");
}
 
Example 12
Project: jdk8u-jdk   File: DataTransferer.java   View Source Code Vote up 5 votes
private boolean isForbiddenToRead (File file, ProtectionDomain protectionDomain)
{
    if (null == protectionDomain) {
        return false;
    }
    try {
        FilePermission filePermission =
                new FilePermission(file.getCanonicalPath(), "read, delete");
        if (protectionDomain.implies(filePermission)) {
            return false;
        }
    } catch (IOException e) {}

    return true;
}
 
Example 13
Project: parabuild-ci   File: RuntimeUtils.java   View Source Code Vote up 5 votes
private static void validateCurrentDir(final File directoryToExecuteIn) throws IOException {
  if (directoryToExecuteIn != null) {
    if (!directoryToExecuteIn.exists())
      throw new IOException("Directory does not exist: \"" + directoryToExecuteIn.getCanonicalPath() + '\"');
    if (!directoryToExecuteIn.isDirectory())
      throw new IOException("Path is not a directory: \"" + directoryToExecuteIn.getCanonicalPath() + '\"');
  }
}
 
Example 14
Project: sstore-soft   File: FileUtil.java   View Source Code Vote up 5 votes
public static String realpath(String path) {
    File f = new File(path);
    String ret = null;
    try {
        ret = f.getCanonicalPath();
    } catch (Exception ex) {
        LOG.warn(ex);
    }
    return (ret);
}
 
Example 15
Project: rapidminer   File: Tools.java   View Source Code Vote up 5 votes
/** Returns the relative path of the first file resolved against the second. */
public static String getRelativePath(File firstFile, File secondFile) throws IOException {
	String canonicalFirstPath = firstFile.getCanonicalPath();
	String canonicalSecondPath = secondFile.getCanonicalPath();

	int minLength = Math.min(canonicalFirstPath.length(), canonicalSecondPath.length());
	int index = 0;
	for (index = 0; index < minLength; index++) {
		if (canonicalFirstPath.charAt(index) != canonicalSecondPath.charAt(index)) {
			break;
		}
	}

	String relPath = canonicalFirstPath;
	int lastSeparatorIndex = canonicalFirstPath.substring(0, index).lastIndexOf(File.separator);
	if (lastSeparatorIndex != -1) {
		String absRest = canonicalSecondPath.substring(lastSeparatorIndex + 1);
		StringBuffer relPathBuffer = new StringBuffer();
		while (absRest.indexOf(File.separator) >= 0) {
			relPathBuffer.append(".." + File.separator);
			absRest = absRest.substring(absRest.indexOf(File.separator) + 1);
		}
		relPathBuffer.append(canonicalFirstPath.substring(lastSeparatorIndex + 1));
		relPath = relPathBuffer.toString();
	}
	return relPath;
}
 
Example 16
Project: zencash-swing-wallet-ui   File: ZCashClientCaller.java   View Source Code Vote up 5 votes
public ZCashClientCaller(String installDir)
	throws IOException
{
	// Detect daemon and client tools installation
	File dir = new File(installDir);
    zcashcli = new File(dir, OSUtil.getZCashCli());

	if (!zcashcli.exists())
	{
		zcashcli = OSUtil.findZCashCommand(OSUtil.getZCashCli());
	}

	if ((zcashcli == null) || (!zcashcli.exists()))
	{
		throw new IOException(
			"The ZENCash installation directory " + installDir + " needs to contain " +
			"the command line utilities zend and zen-cli. zen-cli is missing!");
	}
	
	zcashd = new File(dir, OSUtil.getZCashd());
	if (!zcashd.exists())
	{
	    zcashd = OSUtil.findZCashCommand(OSUtil.getZCashd());
	}
	
	if (zcashd == null || (!zcashd.exists()))
	{
	    throw new IOException(
	    	"The ZENCash command line utility " + zcashcli.getCanonicalPath() + 
	    	" was found, but zend was not found!");
	}
}
 
Example 17
Project: AgentWorkbench   File: Project.java   View Source Code Vote up 5 votes
/**
 * Move project libraries to the specified destination directory.
 *
 * @param destinationDirectoryRootPath the destination directory root path
 * @param messageSuccess the optional message for successful export
 * @param messageFailure the optional message, if the export failed
 * @return the actual path of the resources for the file manager
 */
public String exportProjectRessurcesToDestinationDirectory(String destinationDirectoryRootPath, String messageSuccess, String messageFailure) {

	// --- Define / create destination directory ----------------
	File destinationDir = new File(destinationDirectoryRootPath);
	if (destinationDir.exists()==false) destinationDir.mkdirs();

	// --- Define the target file -------------------------------
	File projectExportFile = new File(destinationDir.getAbsolutePath() + File.separator + this.getProjectFolder() + ".agui");

	// --- Define the export settings ---------------------------
	ProjectExportSettings pExSet = new ProjectExportSettings();
	pExSet.setTargetFile(projectExportFile);
	pExSet.setIncludeAllSetups(false);
	pExSet.setIncludeInstallationPackage(false);

	// --- Do the export ----------------------------------------
	ProjectExportController pExCon = new ProjectExportController(this);
	if (messageSuccess!=null) pExCon.setMessageSuccess(messageSuccess);	
	if (messageFailure!=null) pExCon.setMessageFailure(messageFailure);
	pExCon.exportProject(pExSet, false, false);

	// --- Return the root path for the file manager ------------
	String destinationDirPath = null;
	try {
		destinationDirPath = destinationDir.getCanonicalPath();
	} catch (IOException ioEx) {
		ioEx.printStackTrace();
	}
	return destinationDirPath;
}
 
Example 18
Project: monarch   File: ClusterConfigWithSecurityDUnitTest.java   View Source Code Vote up 5 votes
private String buildSecureClusterConfigZip() throws Exception {
  File clusterDir = lsRule.getTempFolder().newFolder("cluster");
  File clusterSubDir = new File(clusterDir, "cluster");

  String clusterProperties = "mcast-port=0\n" + "log-file-size-limit=8000\n"
      + "security-manager=org.apache.geode.example.security.ExampleSecurityManager";
  FileUtils.writeStringToFile(new File(clusterSubDir, "cluster.properties"), clusterProperties);
  File clusterZip = new File(lsRule.getTempFolder().getRoot(), "cluster_config_security.zip");
  ZipUtils.zipDirectory(clusterDir.getCanonicalPath(), clusterZip.getCanonicalPath());
  FileUtils.deleteDirectory(clusterDir);
  return clusterZip.getCanonicalPath();
}
 
Example 19
Project: faitic-checker   File: ClassicRoutines.java   View Source Code Vote up 4 votes
public static String getAbsolutePath(String relPath, String folderAsReference){
	

	String divider=cpath("/");
	
	int indexofdivider=folderAsReference.lastIndexOf(divider) == folderAsReference.length()-1 ? folderAsReference.lastIndexOf(divider) : folderAsReference.length();
	// if it ends with a /, it is taken as the last /, if not everything is taken (/ in length())
	
	String folderCorrected=folderAsReference.substring(0, indexofdivider) + divider;	// going to parents. Path WITH / !!!
	
	File path=new File(folderCorrected + relPath);
	
	try {
		
		return path.getCanonicalPath();
		
	} catch (IOException e) {

		e.printStackTrace();
		return path.getAbsolutePath();
		
	}
	
}
 
Example 20
Project: jdk8u-jdk   File: SunFontManager.java   View Source Code Vote up 4 votes
private void addDirFonts(String dirName, File dirFile,
                         FilenameFilter filter,
                         int fontFormat, boolean useJavaRasterizer,
                         int fontRank,
                         boolean defer, boolean resolveSymLinks) {
    String[] ls = dirFile.list(filter);
    if (ls == null || ls.length == 0) {
        return;
    }
    String[] fontNames = new String[ls.length];
    String[][] nativeNames = new String[ls.length][];
    int fontCount = 0;

    for (int i=0; i < ls.length; i++ ) {
        File theFile = new File(dirFile, ls[i]);
        String fullName = null;
        if (resolveSymLinks) {
            try {
                fullName = theFile.getCanonicalPath();
            } catch (IOException e) {
            }
        }
        if (fullName == null) {
            fullName = dirName + File.separator + ls[i];
        }

        // REMIND: case compare depends on platform
        if (registeredFontFiles.contains(fullName)) {
            continue;
        }

        if (badFonts != null && badFonts.contains(fullName)) {
            if (FontUtilities.debugFonts()) {
                FontUtilities.getLogger()
                                     .warning("skip bad font " + fullName);
            }
            continue; // skip this font file.
        }

        registeredFontFiles.add(fullName);

        if (FontUtilities.debugFonts()
            && FontUtilities.getLogger().isLoggable(PlatformLogger.Level.INFO)) {
            String message = "Registering font " + fullName;
            String[] natNames = getNativeNames(fullName, null);
            if (natNames == null) {
                message += " with no native name";
            } else {
                message += " with native name(s) " + natNames[0];
                for (int nn = 1; nn < natNames.length; nn++) {
                    message += ", " + natNames[nn];
                }
            }
            FontUtilities.getLogger().info(message);
        }
        fontNames[fontCount] = fullName;
        nativeNames[fontCount++] = getNativeNames(fullName, null);
    }
    registerFonts(fontNames, nativeNames, fontCount, fontFormat,
                     useJavaRasterizer, fontRank, defer);
    return;
}