下面列出了org.apache.commons.io.FilenameUtils#getExtension ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private String getFileEnding(String mime){
if (mime != null) {
if (mime.length() < 5) {
return mime;
} else {
String ret = MimeTool.getExtension(mime);
if (ret.length() > 5) {
return getDefaultFileEnding();
} else if (ret.isEmpty()) {
return FilenameUtils.getExtension(mime);
} else {
return ret;
}
}
}
return getDefaultFileEnding();
}
/**
* Downloads an given Moodle item into the user's device.
* @param item the item to be downloaded.
*/
@NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
void downloadMoodleObject(MoodleModuleContent item) {
String url = item.getFileurl() + "&token=" + ApplicationManager.userCredentials.getMoodleToken();
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, item.getFilename());
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
MimeTypeMap mimetype = MimeTypeMap.getSingleton();
String extension = FilenameUtils.getExtension(item.getFilename());
request.setMimeType(mimetype.getMimeTypeFromExtension(extension));
dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
enqueue = dm.enqueue(request);
}
/**
* composing URI for handling file.
* <p>
* URI form varies as follows depending on extension.<br>
* <ul>
* <li>/bot/{appId}/{botName}/{fileKind} for pdefaults, properties.
* <li>/bot/{appId}/{botName}/{fileKind}/baseName for map, set,
* substitution.
* <li>/bot/{appId}/{botName}/file/baseName.extName for aiml.
* </ul>
* <p>
*
* @param botName
* @param pathName
* @return URI for request
* @throws URISyntaxException
* @since 0.0.9
*/
private URI fileUri(String botName, String pathName)
throws URISyntaxException {
String baseName = FilenameUtils.getBaseName(pathName);
String extName = FilenameUtils.getExtension(pathName);
String fileKind = extName;
String fileName = null;
if (extName.equals("pdefaults") || extName.equals("properties")) {
;
} else if (extName.equals("map") || extName.equals("set")
|| extName.equals("substitution")) {
fileName = baseName;
} else if (extName.equals("aiml")) {
fileKind = "file";
fileName = baseName + "." + extName;
}
return new URI(composeUri("bot", botName, fileKind, fileName)
+ composeParams(null));
}
/**
* Returns the name of the localized transformation file
* if it actually exists, keeps the original in the other case
*
* @param filename name of the requested transformation file
* @return original or localized transformation file to use
*/
protected String getLocalizedProposedFilename(String filename, final WatchService watchService) {
String extension = FilenameUtils.getExtension(filename);
String prefix = FilenameUtils.getPath(filename);
String result = filename;
if (!prefix.isEmpty()) {
watchSubDirectory(prefix, watchService);
}
// the filename may already contain locale information
if (!filename.matches(".*_[a-z]{2}." + extension + "$")) {
String basename = FilenameUtils.getBaseName(filename);
String alternateName = prefix + basename + "_" + getLocale().getLanguage() + "." + extension;
String alternatePath = getSourcePath() + alternateName;
File f = new File(alternatePath);
if (f.exists()) {
result = alternateName;
}
}
result = getSourcePath() + result;
return result;
}
public File epubToPdf(MultipartFile uploadFile) throws Exception {
String filename = uploadFile.getOriginalFilename();
filename = FilenameUtils.getBaseName(filename) + "_" + DateTime.now().toString("yyyyMMdd_HHmmss") + "." + FilenameUtils.getExtension(filename);
filename = FilenameUtils.concat(System.getProperty("java.io.tmpdir"), filename);
File file = new File(filename);
logger.info("saving uploaded ePub file " + uploadFile.getOriginalFilename() + " to " + filename);
FileUtils.writeByteArrayToFile(file, uploadFile.getBytes());
EpubToPdfConverter epubToPdfConverter = new EpubToPdfConverter();
try {
File newPdf = epubToPdfConverter.convert(filename);
return newPdf;
} finally {
FileUtils.deleteQuietly(file);
}
}
@Nullable
protected String getLocalizedTemplateContent(Resources resources, String defaultTemplateName, String locale) {
String localizedTemplate = FilenameUtils.getFullPath(defaultTemplateName)
+ FilenameUtils.getBaseName(defaultTemplateName) +
"_" + locale +
"." + FilenameUtils.getExtension(defaultTemplateName);
return resources.getResourceAsString(localizedTemplate);
}
public static String getCompressFileName(String fileName) {
if(hasCompress(fileName)) {
return fileName;
}
String compressFileName = null;
final String extension = FilenameUtils.getExtension(fileName);
if("js".equalsIgnoreCase(extension)) {
compressFileName = fileName.substring(0, fileName.length() - 3) + ".min.js";
} else if("css".equals(extension)){
compressFileName = fileName.substring(0, fileName.length() - 4) + ".min.css";
}
return compressFileName;
}
@Override
public boolean isValid(File value, ConstraintValidatorContext context) {
if (value != null && value.isFile()) {
String extension = FilenameUtils.getExtension(value.getName());
return equalsIgnoreCase(expectedExtension, extension) && indexOfExtension(value.getName()) > 0;
}
return true;
}
/**
* 只上传文件
*
* @return
* @throws Exception
*/
private FastImageFile crtFastImageFileOnly() 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()
.withFile(in, file.length(), fileExtName)
.withMetaData(metaDataSet)
.build();
}
@Override
protected void tick() {
boolean enable = fileSelector.getSelectedFile() != null;
if (fileSelector.getSelectedFile() != null && fileSelector.getSelectedFile().isFile()) {
enable = false;
String name = FilenameUtils.getExtension(fileSelector.getSelectedFile().getName());
for (String extension : allowedExtensions) {
if (name.equalsIgnoreCase(extension)) {
enable = true;
break;
}
}
getButtonById(100).setLabel(I18n.translate("file_selector.select"));
} else {
getButtonById(100).setLabel(I18n.translate("file_selector.open"));
}
getButtonById(100).setEnabled(enable);
ITextfield textfield = getTextfieldById(1);
if (!textfield.callIsFocused()) {
File currentDir = fileSelector.getCurrentDir();
if (currentDir == null) {
textfield.callSetText("");
} else {
textfield.callSetText(currentDir.getAbsolutePath());
}
}
}
public int importMods(Path sourcePath) throws ModImportException{
try {
String extension = FilenameUtils.getExtension(sourcePath.toString());
if (extension.equalsIgnoreCase("json")){
return importJsonList(sourcePath);
} else if (extension.equalsIgnoreCase("txt")){
return importModsList(sourcePath);
} else {
throw new ModImportException("Cannot import. Invalid file extension.");
}
} catch (JsonSyntaxException | JsonIOException | IOException e){
throw new ModImportException("Cannot import", e);
}
}
/**
* 上传文件,按设定尺寸方式生成缩略图
*
* @return
* @throws Exception
*/
private FastImageFile crtFastImageAndCrtThumbImageBySize() 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(200, 200)
.withFile(in, file.length(), fileExtName)
.withMetaData(metaDataSet)
.build();
}
protected boolean executeScript(ScriptResource file) {
log.info("Executing script " + getScriptName(file));
String filename = file.getName();
String extension = FilenameUtils.getExtension(filename);
if (StringUtils.isNotEmpty(extension)) {
if (extensionHandlers.containsKey(extension)) {
FileHandler handler = extensionHandlers.get(extension);
return handler.run(file);
} else
log.warn("Update script ignored, file handler for extension not found:" +
file.getName());
} else
log.warn("Update script ignored, file extension undefined:" + file.getName());
return false;
}
/**
* @return an error JobStatus if any input is invalid, otherwise JobStatus.VALID
*/
public static JobStatus validateJobParams(SocrataConnectionInfo connectionInfo, GISJob job) {
if (connectionInfo.getUrl().equals("") || connectionInfo.getUrl().equals("https://")) {
return JobStatus.INVALID_DOMAIN;
}
if (!Utils.uidIsValid(job.getDatasetID())) {
return JobStatus.INVALID_DATASET_ID;
}
String fileToPublish = job.getFileToPublish();
if (fileToPublish.equals("")) {
return JobStatus.MISSING_FILE_TO_PUBLISH;
}
File publishFile = new File(fileToPublish);
if (!publishFile.exists() || publishFile.isDirectory()) {
JobStatus errorStatus = JobStatus.FILE_TO_PUBLISH_DOESNT_EXIST;
errorStatus.setMessage(fileToPublish + ": File to publish does not exist");
return errorStatus;
}
String fileExtension = FilenameUtils.getExtension(fileToPublish);
if (!allowedGeoFileToPublishExtensions.contains(fileExtension)) {
return JobStatus.FILE_TO_PUBLISH_INVALID_GIS_FORMAT;
}
return JobStatus.VALID;
}
private void assertMutuallyExclusiveFileAndProperties(File yamlFile, String properties) {
Assert.isTrue(!(yamlFile != null && properties != null), "The options 'file' and 'properties' options "
+ "are mutually exclusive.");
if (yamlFile != null) {
String extension = FilenameUtils.getExtension(yamlFile.getName());
Assert.isTrue((extension.equalsIgnoreCase("yml") || extension.equalsIgnoreCase("yaml")),
"The file should be YAML file");
}
}
/**
* 缩略图文件URL/ID编辑 <br>
* 取缩略图
*
* @param orgiUrl 原图URL
* @param width 文件宽
* @param height 文件高
* @return 缩略图URl
*/
public static String getThumbUrl(String orgiUrl, int width, int height) {
if (orgiUrl == null) {
return null;
}
String extension = FilenameUtils.getExtension(orgiUrl);
if (extension == null) {
return orgiUrl;
}
if ("jpg".equalsIgnoreCase(extension)) {
// 缩略图
} else if ("png".equalsIgnoreCase(extension)) {
// 缩略图
} else {
return orgiUrl;
}
int extensionPos = orgiUrl.length() - extension.length() - 1;
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(orgiUrl.substring(0, extensionPos));
stringBuffer.append("_").append(width).append("x").append(height);
stringBuffer.append(orgiUrl.substring(extensionPos));
return stringBuffer.toString();
}
/**
* The method activateSetOnDragDropped controlling what happens when something is dropped on window.
* Implemented activateSetOnDragDropped to select the module according to the dropped file type and open dropped file
* @param event - DragEvent
*/
public static void activateSetOnDragDropped(DragEvent event){
Dragboard dragboard = event.getDragboard();
boolean hasFileDropped = false;
if (dragboard.hasFiles()) {
hasFileDropped = true;
for (File selectedFile:dragboard.getFiles()) {
final String extension = FilenameUtils.getExtension(selectedFile.getName());
String[] rawDataFile = {"cdf","nc","mzData","mzML","mzXML","raw"};
final Boolean isRawDataFile = Arrays.asList(rawDataFile).contains(extension);
final Boolean isMZmineProject = extension.equals("mzmine");
Class<? extends MZmineRunnableModule> moduleJavaClass = null;
if(isMZmineProject)
{
moduleJavaClass = ProjectLoadModule.class;
} else if(isRawDataFile){
moduleJavaClass = RawDataImportModule.class;
}
if(moduleJavaClass != null){
ParameterSet moduleParameters =
MZmineCore.getConfiguration().getModuleParameters(moduleJavaClass);
if(isMZmineProject){
moduleParameters.getParameter(projectFile).setValue(selectedFile);
} else if (isRawDataFile){
File fileArray[] = { selectedFile };
moduleParameters.getParameter(fileNames).setValue(fileArray);
}
ParameterSet parametersCopy = moduleParameters.cloneParameterSet();
MZmineCore.runMZmineModule(moduleJavaClass, parametersCopy);
}
}
}
event.setDropCompleted(hasFileDropped);
event.consume();
}
public File downFileToLocal(String url, String suffix) throws IOException {
String actualSuffix;
if (StringUtils.isNotBlank(suffix)) {
actualSuffix = suffix.startsWith(".") ? suffix : DOT + suffix;
} else {
String extension = FilenameUtils.getExtension(url);
if (StringUtils.isNotBlank(extension)) {
actualSuffix = DOT + extension;
} else {
actualSuffix = "";
}
}
ResponseExtractor<ResponseEntity<File>> responseExtractor = new ResponseExtractor<ResponseEntity<File>>() {
@Override
public ResponseEntity<File> extractData(ClientHttpResponse response) throws IOException {
File downFile = File.createTempFile("download", actualSuffix);
log.info("down {} to local:{}", url, downFile.getPath());
FileCopyUtils.copy(response.getBody(), new FileOutputStream(downFile));
return ResponseEntity.status(response.getStatusCode()).headers(response.getHeaders()).body(downFile);
}
};
ResponseEntity<File> responseEntity = restTemplate.execute(url, HttpMethod.GET, null, responseExtractor);
if (responseEntity != null) {
return responseEntity.getBody();
}
log.error("fail to downFileToLocal {} ", url);
throw new IOException("fail to downFileToLocal");
}
/**
* Gets the extension for the given filename, if an alias is found then the
* value of the alias is returned as well. For instance if in the settings
* you have <code>converter.alias.eft=txt</code> then a file named test.eft
* will be considered a txt.
*
* @param fileNameOrExtension file name or just the extension
*
* @return the real extension to use
*/
public static String getExtension(String fileNameOrExtension) {
String ext = fileNameOrExtension;
if (fileNameOrExtension.contains("."))
ext = FilenameUtils.getExtension(fileNameOrExtension.toLowerCase());
String alias = Context.get().getProperties().getProperty("converter.alias." + ext);
if (StringUtils.isNotEmpty(alias))
ext = alias;
return ext.toLowerCase();
}
public static boolean isExcelFile(String filename) {
String extension = FilenameUtils.getExtension(filename);
return ExcelFileExtensions.getExcel().contains(extension);
}