下面列出了怎么用org.apache.commons.io.FilenameUtils的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* スクリプトを読み込み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;
}
}
/**
* 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 + "\"");
}
}
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);
}
}
@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;
}
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();
}
}
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;
}
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();
}
}
@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));
}
}
}
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
);
}
/**
* 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();
}
}
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;
}
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;
}
/**
* 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();
}
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);
}
}
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);
}
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;
}
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;
}
@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", "");
}
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;
}
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));
}
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;
}
/**
* 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);
}
@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"));
}
/**
* 是否是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;
}
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;
}
/**
* 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;
}