类org.apache.commons.io.FilenameUtils源码实例Demo

下面列出了怎么用org.apache.commons.io.FilenameUtils的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: logbook   文件: ScriptLoader.java
/**
 * スクリプトを読み込みEventListenerの実装を取得する<br>
 *
 * @param script スクリプト
 * @return スクリプトにより実装されたEventListener、スクリプトエンジンが見つからない、もしくはコンパイル済み関数がEventListenerを実装しない場合null
 * @throws IOException
 * @throws ScriptException
 */
@CheckForNull
public EventListener getEventListener(Path script) throws IOException, ScriptException {
    try (BufferedReader reader = Files.newBufferedReader(script, StandardCharsets.UTF_8)) {
        // 拡張子からScriptEngineを取得
        String ext = FilenameUtils.getExtension(script.toString());
        ScriptEngine engine = this.manager.getEngineByExtension(ext);
        if (engine != null) {
            // eval
            engine.eval(reader);
            // 実装を取得
            EventListener listener = ((Invocable) engine).getInterface(EventListener.class);

            if (listener != null) {
                return new ScriptEventAdapter(listener, script);
            }
        }
        return null;
    }
}
 
源代码2 项目: projectforge-webapp   文件: ResponseUtils.java
/**
 * Prepares download of a file. The content type will be detected automatically by the file name.
 *
 * @param filename Virtual file name. Any path infos will be truncated.
 * @param response
 * @param ctx der Servletcontext
 * @param attach Download as Attachment
 */
public static void prepareDownload(String filename, HttpServletResponse response, ServletContext ctx, boolean attach)
{
  String mimeType = null;
  try {
    mimeType = ctx.getMimeType(filename);
  } catch (Exception ex) {
    log.info("Exception while getting mime-type (using application/binary): " + ex);
  }
  if (mimeType == null) {
    response.setContentType("application/binary");
  } else {
    response.setContentType(mimeType);
  }
  log.debug("Using content-type " + mimeType);
  final String filenameWithoutPath = FilenameUtils.getName(filename);
  if (attach == true) {
    response.setHeader("Content-disposition", "attachment; filename=\"" + filenameWithoutPath + "\"");
  } else {
    response.setHeader("Content-disposition", "inline; filename=\"" + filenameWithoutPath + "\"");
  }
}
 
源代码3 项目: gemfirexd-oss   文件: ConfigurationUtils.java
public static void writeConfig(String configDirPath, Configuration configuration, boolean forceWrite) throws Exception {
  File configDir = new File(configDirPath);
  if (!configDir.exists()) {
    configDir.mkdirs();
  }
  String dirPath = FilenameUtils.concat(configDirPath, configuration.getConfigName());
  File file = new File(dirPath);
  if (!file.exists()) {
    if (!file.mkdir()) {
      //TODO : Throw some exception instead of quietly returning 
      throw new Exception("Cannot create directory on this machine");
    }
  }
    
  if(configuration.isPropertiesFileChanged() || forceWrite) {
    writePropeties(dirPath, configuration);
  }
  if (configuration.isCacheXmlModified() || forceWrite) {
    writeCacheXml(dirPath, configuration);
  }
}
 
源代码4 项目: ghidra   文件: CrushedPNGFileSystem.java
@Override
public void open(TaskMonitor monitor) throws IOException, CryptoException, CancelledException {
	BinaryReader reader = new BinaryReader(provider, false);

	monitor.setMessage("Opening iOS Crushed PNG...");
	this.png = new ProcessedPNG(reader, monitor);

	String uncrushedPngFilename = getName();

	//Remove the .png extension and then replace with .uncrushed.png extension
	if ("png".equalsIgnoreCase(FilenameUtils.getExtension(uncrushedPngFilename))) {
		uncrushedPngFilename =
			FilenameUtils.removeExtension(uncrushedPngFilename) + ".uncrushed.png";
	}

	pngGFile = GFileImpl.fromFilename(this, root, uncrushedPngFilename, false, 1, null);
}
 
/**
 * 文件类型的附件
 */
@RequestMapping(value = "new/file")
public String newFile(@RequestParam("taskId") String taskId, @RequestParam(value = "processInstanceId", required = false) String processInstanceId,
                      @RequestParam("attachmentName") String attachmentName, @RequestParam(value = "attachmentDescription", required = false) String attachmentDescription,
                      @RequestParam("file") MultipartFile file, HttpSession session) {
    try {
        String attachmentType = file.getContentType() + ";" + FilenameUtils.getExtension(file.getOriginalFilename());
        identityService.setAuthenticatedUserId(UserUtil.getUserFromSession(session).getId());
        Attachment attachment = taskService.createAttachment(attachmentType, taskId, processInstanceId, attachmentName, attachmentDescription,
                file.getInputStream());
        taskService.saveAttachment(attachment);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "redirect:/chapter6/task/getform/" + taskId;
}
 
源代码6 项目: sailfish-core   文件: ZipReport.java
private void zipFile(IWorkspaceDispatcher dispatcher, ZipOutputStream zip, String relativeFile, String zipFolder) throws IOException {

        zipFolder = buildPath(zipFolder, FilenameUtils.getName(relativeFile));

        byte[] buf = new byte[1024];

        zip.putNextEntry(new ZipEntry(zipFolder));

        try (InputStream inputStream = new FileInputStream(dispatcher.getFile(FolderType.REPORT, relativeFile))) {
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                zip.write(buf, 0, len);
            }
        } finally {
            zip.closeEntry();
        }
    }
 
源代码7 项目: xds-ide   文件: CompileDriver.java
public List<String> getModuleList(String srcFile, String prjFile) {
    final List<String> moduleList = new ArrayList<String>();
    if (prjFile == null) {
        doCompile( sdk, CompilationMode.MAKE_MODULE_LIST
                 , srcFile, null
                 , new ModuleListListener(moduleList, FilenameUtils.getFullPath(srcFile)) );
    } else {
        File workDirectory = (new File(prjFile)).getParentFile();
        String arguments = "-prj=" + prjFile; //$NON-NLS-1$
        doCompile( sdk, CompilationMode.MAKE_MODULE_LIST
                 , srcFile, workDirectory
                 , new ModuleListListener(moduleList, FilenameUtils.getFullPath(srcFile)) 
                 , arguments );
    }
    return moduleList;
}
 
源代码8 项目: api-mining   文件: MAPO.java
public static void main(final String[] args) throws Exception {

		// Runtime parameters
		final Parameters params = new Parameters();
		final JCommander jc = new JCommander(params);

		try {
			jc.parse(args);

			// Mine project
			System.out.println("Processing " + FilenameUtils.getBaseName(params.arffFile) + "...");
			mineAPICallSequences(params.arffFile, params.outFolder, 0.4, params.minSupp);

		} catch (final ParameterException e) {
			System.out.println(e.getMessage());
			jc.usage();
		}

	}
 
源代码9 项目: mrgeo   文件: ShapefileReader.java
@SuppressFBWarnings(value = {"WEAK_FILENAMEUTILS",
    "PATH_TRAVERSAL_IN"}, justification = "Correctly filtered parameters")
private void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException
{
  fileName = in.readUTF();
  source = Source.values()[in.readInt()];

  if (source == Source.FILE)
  {
    File f = new File(FilenameUtils.getFullPath(fileName), FilenameUtils.getName(fileName));
    if (f.exists())
    {
      load(fileName);
    }
  }
  else
  {
    if (HadoopFileUtils.exists(fileName))
    {
      load(new Path(fileName));
    }
  }
}
 
源代码10 项目: xds-ide   文件: SdkIniFileWriter.java
private String mkRelPath(String home, String path) {
    if (path == null || Sdk.NOT_SUPPORTED.equals(path)) {
        return path;
    }
    String file = FilenameUtils.normalize(path);
    boolean isParent;
    if (File.separatorChar == '\\') {
        isParent = file.toLowerCase().startsWith(home.toLowerCase()); // Win
    } else {
        isParent = file.startsWith(home); // Linux
    }
    if (isParent) {
        file = file.substring(home.length());
        if (file.startsWith(File.separator)) {
            file = file.substring(1);
        }
    }
    return file;
}
 
/**
 * Returns the correct name of a resource to be saved in the system.
 * @param masterFileName Original file name
 * @param size Order number of the file being saved
 * @param langCode Language code of file being saved
 * @return Correct name to save file
 */
String getNewInstanceFileName(String masterFileName, int size, String langCode) {
    String baseName = FilenameUtils.getBaseName(masterFileName);
    String extension = FilenameUtils.getExtension(masterFileName);
    String suffix = "";
    if (size >= 0) {
        suffix += "_d" + size;
    }
    if (langCode != null) {
        suffix += "_" + langCode;
    }
    return this.createFileName(
            super.getMultiFileUniqueBaseName(baseName, suffix, extension),
            extension
    );
}
 
源代码12 项目: Mundus   文件: KryoManager.java
/**
 * Saves a scene.
 *
 * @param context
 *            project context of the scene
 * @param scene
 *            scene to save
 */
public void saveScene(ProjectContext context, Scene scene) {
    try {
        String sceneDir = FilenameUtils.concat(context.path + "/" + ProjectManager.PROJECT_SCENES_DIR,
                scene.getName() + "." + ProjectManager.PROJECT_SCENE_EXTENSION);

        Output output = new Output(new FileOutputStream(sceneDir));

        SceneDescriptor descriptor = DescriptorConverter.convert(scene);
        kryo.writeObject(output, descriptor);

        output.flush();
        output.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}
 
源代码13 项目: repositoryminer   文件: RepositoryMinerFindBugs.java
private List<String> getFiles(String dir) {
	Collection<File> files = FileUtils.listFiles(new File(dir), EXTENSION_FILE_FILTER, true);
	List<String> filepaths = new ArrayList<String>(files.size());
	for (File f : files) {
		filepaths.add(FilenameUtils.normalize(f.getAbsolutePath().substring(dir.length() + 1), true));
	}
	return filepaths;
}
 
源代码14 项目: extract   文件: PinnedHttpClientBuilder.java
public static KeyStore createTrustStore(final String trustStorePath, final String trustStorePassword)
	throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException {

	final String trustStoreExtension = FilenameUtils.getExtension(trustStorePath).toUpperCase(Locale.ROOT);
	final String trustStoreType;

	// Key store types are defined in Oracle's Cryptography Standard Algorithm Name Documentation:
	// http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#KeyStore
	if (trustStoreExtension.equals("P12")) {
		trustStoreType = "PKCS12";
	} else {
		trustStoreType = KeyStore.getDefaultType();
	}

	final KeyStore trustStore = KeyStore.getInstance(trustStoreType);

	try (
		final InputStream input = new BufferedInputStream(new FileInputStream(trustStorePath))
	) {
		if (trustStoreExtension.equals("PEM") || trustStoreExtension.equals("DER")) {
			final X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
				.generateCertificate(input);

			// Create an empty key store.
			// This operation should never throw an exception.
			trustStore.load(null, null);
			trustStore.setCertificateEntry(Integer.toString(1), certificate);
		} else {
			trustStore.load(input, trustStorePassword.toCharArray());
		}
	}

	return trustStore;
}
 
源代码15 项目: swaggerhub-maven-plugin   文件: SwaggerHubUpload.java
/**
 * Used to format the output folder as SwaggerHub expects it.
 * @param path
 * @return
 */
private String getOutputFolder(String path){

    //Remove the portion of the path which is prior to our repositories file path
    path = StringUtils.removeStart(FilenameUtils.getFullPath(path), REPOSITORY_LOCATION);
    //Return the path without leading and ending / and ensures the file path uses forward slashes instead of backslashes
    return StringUtils.strip(StringUtils.strip(path,"/"),"\\").replace("\\", "/");
}
 
/**
 * 上传文件,按默认方式生成缩略图
 *
 * @return
 * @throws Exception
 */
private FastImageFile crtFastImageAndCrtThumbImageByDefault() throws Exception {
    InputStream in = TestUtils.getFileInputStream(TestConstants.PERFORM_FILE_PATH);
    Set<MetaData> metaDataSet = createMetaData();
    File file = TestUtils.getFile(TestConstants.PERFORM_FILE_PATH);
    String fileExtName = FilenameUtils.getExtension(file.getName());

    return new FastImageFile.Builder()
            .withThumbImage()
            .withFile(in, file.length(), fileExtName)
            .withMetaData(metaDataSet)
            .build();
}
 
源代码17 项目: website   文件: LicenceService.java
public boolean generateFile(Licence licence) throws Exception {
	finalizeLicence(licence);
	WatermarkWriter watermarkWriter = WatermarkWriterFactory.create(FilenameUtils.getExtension(licence.getOriginalFileName()));
	try {
		watermarkWriter.writeWatermark(sourceLicenceFile(licence), targetLicenceFile(licence), WatermarkFactory.fromLicence(licence), licence.getPageLayout());
		return true;
	} catch (IOException e) {
		throw new Exception("Unable to generate PDF", e);
	}
}
 
源代码18 项目: netbeans-mmd-plugin   文件: ExtraFile.java
public boolean isSame(@Nullable final File baseFolder, @Nonnull final MMapURI file) {
  final File theFile = this.fileUri.asFile(baseFolder);
  final File thatFile = file.asFile(baseFolder);

  final String theFilePath = FilenameUtils.normalize(theFile.getAbsolutePath());
  final String thatFilePath = FilenameUtils.normalize(thatFile.getAbsolutePath());

  return theFilePath.equals(thatFilePath);
}
 
源代码19 项目: micro-integrator   文件: ScenarioTestBase.java
protected List<Request> extractRequests(String testCase) throws IOException {
    String relativeRequestFolderLocation = appendSourceFolder(testCase, ScenarioConstants.REQUEST);
    List<String> requestFiles = getFilesFromSourceDirectory(relativeRequestFolderLocation);
    ArrayList<Request> requestArray = new ArrayList();

    for (String file : requestFiles) {
        String fileContent = getFileContent(relativeRequestFolderLocation, file);
        String header = FilenameUtils.removeExtension(file);
        requestArray.add(new Request(fileContent, header));
    }
    return requestArray;
}
 
源代码20 项目: knox   文件: DefaultTopologyService.java
private Topology loadTopologyAttempt(File file) throws IOException, SAXException {
  Topology topology;
  try (InputStream in = FileUtils.openInputStream(file)) {
    topology = parse(in);
    if (topology != null) {
      topology.setUri(file.toURI());
      topology.setName(FilenameUtils.removeExtension(file.getName()));
      topology.setTimestamp(file.lastModified());
    }
  }
  return topology;
}
 
源代码21 项目: studio   文件: BlobAwareContentRepositoryTest.java
@Test
public void getContentChildrenWithRemoteTest() {
    RepositoryItem item = new RepositoryItem();
    item.path = PARENT_PATH;
    item.name = FilenameUtils.getName(POINTER_PATH);
    when(local.getContentChildren(SITE, PARENT_PATH)).thenReturn(new RepositoryItem[] { item });

    RepositoryItem[] result = proxy.getContentChildren(SITE, PARENT_PATH);

    assertNotNull(result);
    assertEquals(result.length, 1);
    assertEquals(result[0].path, PARENT_PATH);
    assertEquals(result[0].name, FilenameUtils.getName(ORIGINAL_PATH));
}
 
@Before
public void setUp() throws Exception {
    Configurator.initialize(null, "config/log4j2.xml");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

    String SSL_TRUSTSTORE_PATH = "certs/truststore.jks";
    String SSL_TRUSTSTORE_PW = "changeit";
    String SSL_KEYSTORE_PATH = "certs/jmeter-keystore.jks";
    String SSL_KEYSTORE_PW = "changeit";

    System.setProperty("javax.net.ssl.keyStore", SSL_KEYSTORE_PATH);
    System.setProperty("javax.net.ssl.keyStorePassword", SSL_KEYSTORE_PW);
    System.setProperty("javax.net.ssl.keyStoreType",
            FilenameUtils.getExtension(SSL_KEYSTORE_PATH).toLowerCase().equals("jks") ? "JKS" : "PKCS12");

    System.setProperty("javax.net.ssl.trustStore", SSL_TRUSTSTORE_PATH);
    System.setProperty("javax.net.ssl.trustStorePassword", SSL_TRUSTSTORE_PW);
    System.setProperty("javax.net.ssl.trustStoreType",
            FilenameUtils.getExtension(SSL_TRUSTSTORE_PATH).toLowerCase().equals("jks") ? "JKS" : "PKCS12");

    client = RestClient.builder(new HttpHost("localhost", Integer.parseInt("9200"), "https"))
            .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setConnectTimeout(5000)
                    .setSocketTimeout((int) 200L))
            .setFailureListener(new RestClient.FailureListener() {
                @Override
                public void onFailure(Node node) {
                    System.err.println("Error with node: " + node.toString());
                }
            }).setMaxRetryTimeoutMillis(60000).build();
    sender = new ElasticSearchMetricSender(client, "test_" + sdf.format(new Date()), "logstashTest",
            "logstashTest", "");
}
 
源代码23 项目: MtgDesktopCompanion   文件: MTGControler.java
public MTGCardsExport getAbstractExporterFromExt(File f) {
	String ext = FilenameUtils.getExtension(f.getAbsolutePath());

	for (MTGCardsExport ace : getPlugins(MTGCardsExport.class)) {
		if (ace.getFileExtension().endsWith(ext))
			return ace;
	}
	return null;
}
 
源代码24 项目: ghidra   文件: BatchSegregatingCriteria.java
public BatchSegregatingCriteria(Loader loader, Collection<LoadSpec> loadSpecs,
		ByteProvider provider) {
	for (LoadSpec loadSpec : loadSpecs) {
		groupLoadSpecs.add(new BatchGroupLoadSpec(loadSpec));
	}
	this.loader = loader.getName();
	fileExt = FilenameUtils.getExtension(loader.getPreferredFileName(provider));
}
 
源代码25 项目: studio   文件: AbstractUpgradeOperation.java
private static String getGitPath(String path) {
    Path gitPath = Paths.get(path);
    gitPath = gitPath.normalize();
    try {
        gitPath = Paths.get(FILE_SEPARATOR).relativize(gitPath);
    } catch (IllegalArgumentException e) {
        logger.debug("Path: " + path + " is already relative path.");
    }
    if (StringUtils.isEmpty(gitPath.toString())) {
        return ".";
    }
    String toRet = gitPath.toString();
    toRet = FilenameUtils.separatorsToUnix(toRet);
    return toRet;
}
 
源代码26 项目: neembuu-uploader   文件: NUZipFileGenerator.java
/**
 * Get all accounts.
 * @return Returns all the account classes.
 */
private Collection<File> getAllAccounts(){
    return FileUtils.listFiles(new File(accountsDirectory), new IOFileFilter() {

        @Override
        public boolean accept(File file) {
            return FilenameUtils.isExtension(file.getName(), "class");
        }

        @Override
        public boolean accept(File dir, String name) {
            return dir.getName().equals("accounts");
        }
    }, null);
}
 
源代码27 项目: jqm   文件: ServiceSimple.java
@GET
@Path("stdout")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public InputStream getLogOut(@QueryParam("id") int id)
{
    res.setHeader("Content-Disposition", "attachment; filename=" + id + ".stdout.txt");
    return getFile(FilenameUtils.concat("./logs", StringUtils.leftPad("" + id, 10, "0") + ".stdout.log"));
}
 
源代码28 项目: kbase-doc   文件: FileExtensionUtils.java
/**
 * 是否是Excel文件
 * @author eko.zhan at Aug 7, 2018 11:33:06 AM
 * @param filename
 * @return
 */
public static Boolean isExcel(String filename){
	String[] arr = new String[]{"xls", "xlsx"};
	String extension = FilenameUtils.getExtension(filename).toLowerCase();
	if (ArrayUtils.contains(arr, extension)){
		return true;
	}
	return false;
}
 
源代码29 项目: phone   文件: PrintFileList.java
public static String clearFileType(String filePath){
	if (clearFileType) {
		String fileType = FilenameUtils.getExtension(filePath);
		if (fileType.length()>0) {
			filePath = filePath.substring(0, filePath.length()-fileType.length()-1);
		}
	}
	return filePath;
}
 
源代码30 项目: sejda   文件: PdfFileSourceListAdapter.java
/**
 * Parse fileset definitions <filelist><fileset>[...]</fileset></filelist> ignoring the rest of the document
 * 
 * @param doc
 * @return a list of string matching the contents of the <filelist><fileset> tags in the document
 * @throws XPathExpressionException
 */
private List<String> parseFileSets(Document doc, File configFile) throws XPathExpressionException {
    List<String> result = new ArrayList<>();

    NodeList nodeList = getNodeListMatchingXpath("//filelist/fileset/file", doc);
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        Node fileSet = node.getParentNode();

        String parentDirPath = nullSafeGetStringAttribute(fileSet, "dir");
        if (parentDirPath == null) {
            parentDirPath = configFile.getAbsoluteFile().getParent();
        }

        String filePath = extractFilePath(node);

        // warn if file in fileset is using absolute path mode
        if (FilenameUtils.getPrefixLength(filePath) > 0) {
            LOG.warn("File " + filePath + " in fileset "
                    + StringUtils.defaultIfBlank(nullSafeGetStringAttribute(fileSet, "dir"), "")
                    + " seems to be an absolute path. Will _not_ be resolved relative to the <fileset>, but as an absolute path. Normally you would want to use relative paths in a //filelist/fileset/file, and absolute paths in a //filelist/file.");
        }

        result.add(FilenameUtils.concat(parentDirPath, filePath));
    }

    return result;
}
 
 类所在包
 同包方法