下面列出了org.apache.commons.io.FilenameUtils#getName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static File copyTranscriptFile(TrpPage p, String path, ExportCache cache) throws IOException, JAXBException {
if (p.getTranscripts().isEmpty()) {
return null;
}
String xmlFn = "Transcript_"+p.getPageNr()+".xml";
TrpTranscriptMetadata tmd = p.getTranscripts().get(p.getTranscripts().size()-1);
URL u = tmd.getUrl();
if (u.getProtocol().toLowerCase().contains("file")) {
logger.debug("path: "+u.getPath());
xmlFn = FilenameUtils.getName(FileUtils.toFile(u).getAbsolutePath());
}
else if (u.getProtocol().toLowerCase().contains("http")) {
// parse filename from
String fn = getFilenameFromUrl(u);
if (fn!=null)
xmlFn = fn;
}
return copyTranscriptFile(p, path, xmlFn, cache);
}
private void toIndex(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
try (Writer writer = response.getWriter()) {
WebContext webContext = new WebContext(request, response, request.getServletContext());
webContext.setVariable("baseUrl", resolveBaseUrl(request));
String lang = request.getParameter("lang");
if (StringUtils.isBlank(lang)) {
lang = "zh-cn";
}
webContext.setVariable("lang", lang);
webContext.setVariable("getApisUrl", resolveBaseUrl(request));
configResolver.obtainConfig(request).forEach((k, v) -> webContext.setVariable((String) k, v));
String templateName = FilenameUtils.getName("index.html");
templateEngine.process(templateName, webContext, writer);
}
}
/**
* 下载文件
*/
public static void downloadFile(HttpServletResponse response, String filePath) {
try {
String originalFileName = FilenameUtils.getName(filePath);
String downloadedFileName = new String(originalFileName.getBytes("GBK"), "ISO8859_1"); // 防止中文乱码
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename=\"" + downloadedFileName + "\"");
InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
StreamUtil.copyStream(inputStream, outputStream);
} catch (Exception e) {
logger.error("下载文件出错!", e);
throw new RuntimeException(e);
}
}
public String getResourceNameFromLocation() {
String fileName = "pageSource";
try {
String location = driver().getCurrentUrl();
URL u = new URL(location);
String file = FilenameUtils.getName(u.getPath());
file = file.replaceAll("^(.*?)(\\.html?)?$", "$1");
if (!"".equals(file)) {
fileName = file;
}
} catch (MalformedURLException e) {
// ignore
}
return fileName;
}
private void uploadSourceDocument(ZipFile zip, ZipEntry entry, Project project,
String aFileType)
throws IOException, UIMAException
{
String fileName = FilenameUtils.getName(entry.toString());
InputStream zipStream = zip.getInputStream(entry);
SourceDocument document = new SourceDocument();
document.setName(fileName);
document.setProject(project);
document.setFormat(aFileType);
// Meta data entry to the database
// Import source document to the project repository folder
documentRepository.uploadSourceDocument(zipStream, document);
}
/**
* 获取文件名,含后缀
* @param path
*/
public static String getName(String path){
if(path != null && !"".equals(path.trim())){
return FilenameUtils.getName(path);
}
return "";
}
public static String getFilenameFromUrl(String url)
{
if (url == null)
return null;
try
{
// Add a protocol if none found
if (! url.contains("//"))
url = "http://" + url;
URL uri = new URL(url);
String result = FilenameUtils.getName(uri.getPath());
if (result == null || result.isEmpty())
return null;
if (result.contains(".."))
return null;
return result;
}
catch (MalformedURLException e)
{
return null;
}
}
public static File copyImgFile(TrpPage p, URL u, String path) throws IOException {
String imgFn = "Image_"+p.getPageNr();
if (u.getProtocol().toLowerCase().contains("file")) {
logger.debug("path: "+u.getPath());
imgFn = FilenameUtils.getName(FileUtils.toFile(u).getAbsolutePath());
}
else if (u.getProtocol().toLowerCase().contains("http")) {
// parse filename from
String fn = getFilenameFromUrl(u);
if (fn!=null)
imgFn = fn;
}
return copyImgFile(u, path, imgFn);
}
@Override
public String getName() {
String fileName = fileItem.getName();
if (fileName != null) {
fileName = FilenameUtils.getName(fileName);
}
return fileName;
}
@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));
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
// Process only multipart requests.
if (ServletFileUpload.isMultipartContent(request)) {
// Create a factory for disk-based file items.
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler.
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request.
try {
@SuppressWarnings("unchecked")
List<FileItem> items = upload.parseRequest(request);
AttachmentId id = null;
String waveRefStr = null;
FileItem fileItem = null;
for (FileItem item : items) {
// Process only file upload - discard other form item types.
if (item.isFormField()) {
if (item.getFieldName().equals("attachmentId")) {
id = AttachmentId.deserialise(item.getString());
}
if (item.getFieldName().equals("waveRef")) {
waveRefStr = item.getString();
}
} else {
fileItem = item;
}
}
if (id == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No attachment Id in the request.");
return;
}
if (waveRefStr == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No wave reference in request.");
return;
}
WaveletName waveletName = AttachmentUtil.waveRef2WaveletName(waveRefStr);
ParticipantId user = sessionManager.getLoggedInUser(request.getSession(false));
boolean isAuthorized = waveletProvider.checkAccessPermission(waveletName, user);
if (!isAuthorized) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
// Get only the file name not whole path.
if (fileItem != null && fileItem.getName() != null) {
String fileName = FilenameUtils.getName(fileItem.getName());
service.storeAttachment(id, fileItem.getInputStream(), waveletName, fileName, user);
response.setStatus(HttpServletResponse.SC_CREATED);
String msg =
String.format("The file with name: %s and id: %s was created successfully.",
fileName, id);
LOG.fine(msg);
response.getWriter().print("OK");
response.flushBuffer();
}
} catch (Exception e) {
LOG.severe("Upload error", e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"An error occurred while upload the file : " + e.getMessage());
}
} else {
LOG.severe("Request contents type is not supported by the servlet.");
response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
"Request contents type is not supported by the servlet.");
}
}
private String getFileName(int position) {
return mCategoryName + "/" + FilenameUtils.getName(mImageUrls[position]);
}
public static File extractFile(File zipFile, String path, File destDir) {
destDir.mkdirs();
new File(destDir, path).delete();
//unzip -j taobao-android-debug.apk res/drawable/abc_wb_textfield_cdf.jpg -d .
boolean success = CmdExecutor.execute("", "unzip", "-o", "-j", zipFile.getAbsolutePath(), path, "-d",
destDir.getAbsolutePath());
if (success) {
return new File(destDir, FilenameUtils.getName(path));
}
return ZipUtils.extractZipFileToFolder(zipFile, path, destDir);
}
public SimilarPluginFileFilter(String path) {
String fileName = FilenameUtils.getName(path);
// Convert "org.apache.ant.source_1.8.2.v20120109-1030" -> "org.apache.ant.source.*[.]jar"
fileNameExpr = fileName.replaceFirst("_.*[.]jar$", "") + ".*[.]jar"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
ActionResult<Wo<WoObject>> execute(EffectivePerson effectivePerson, String id, String callback, byte[] bytes,
FormDataContentDisposition disposition) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo<WoObject>> result = new ActionResult<>();
Attachment attachment = emc.find(id, Attachment.class);
if (null == attachment) {
throw new ExceptionAttachmentNotExistCallback(callback, id);
}
if ((!StringUtils.equals(effectivePerson.getDistinguishedName(), attachment.getPerson()))
&& (!attachment.getEditorList().contains(effectivePerson.getDistinguishedName()))) {
throw new ExceptionAttachmentAccessDeniedCallback(effectivePerson, callback, attachment);
}
StorageMapping mapping = ThisApplication.context().storageMappings().get(Attachment.class,
attachment.getStorage());
if (null == mapping) {
throw new ExceptionStorageNotExistCallback(callback, attachment.getStorage());
}
attachment.setLastUpdatePerson(effectivePerson.getDistinguishedName());
/** 禁止不带扩展名的文件上传 */
/** 文件名编码转换 */
String fileName = new String(disposition.getFileName().getBytes(DefaultCharset.charset_iso_8859_1),
DefaultCharset.charset);
fileName = FilenameUtils.getName(fileName);
if (StringUtils.isEmpty(FilenameUtils.getExtension(fileName))) {
throw new ExceptionEmptyExtensionCallback(callback, fileName);
}
/** 不允许不同的扩展名上传 */
if (!Objects.equals(StringUtils.lowerCase(FilenameUtils.getExtension(fileName)),
attachment.getExtension())) {
throw new ExceptionExtensionNotMatchCallback(callback, fileName, attachment.getExtension());
}
emc.beginTransaction(Attachment.class);
attachment.updateContent(mapping, bytes);
emc.check(attachment, CheckPersistType.all);
emc.commit();
/** 通知所有的共享和共享编辑人员 */
List<String> people = new ArrayList<>();
people = ListUtils.union(attachment.getShareList(), attachment.getEditorList());
people.add(attachment.getPerson());
for (String o : ListTools.trim(people, true, true)) {
if (!StringUtils.equals(o, effectivePerson.getDistinguishedName())) {
this.message_send_attachment_editorModify(attachment, effectivePerson.getDistinguishedName(), o);
}
}
ApplicationCache.notify(Attachment.class, attachment.getId());
WoObject woObject = new WoObject();
woObject.setId(attachment.getId());
Wo<WoObject> wo = new Wo<>(callback, woObject);
result.setData(wo);
return result;
}
}
public String getSuffix () {
return FilenameUtils.getName(getKey());
}
private static String filename(final Path path) {
return FilenameUtils.getName(string(path));
}
private void readMPQs() {
if (fileTreeNodes == null) {
fileTreeNodes = new PatriciaTrie<>();
fileTreeCofNodes = new PatriciaTrie<>();
} else {
fileTreeNodes.clear();
fileTreeCofNodes.clear();
}
BufferedReader reader = null;
try {
//if (options_useExternalList.isChecked()) {
reader = Gdx.files.internal(ASSETS + "(listfile)").reader(4096);
//} else {
// try {
// reader = new BufferedReader(new InputStreamReader((new ByteArrayInputStream(mpq.readBytes("(listfile)")))));
// } catch (Throwable t) {
// reader = Gdx.files.internal(ASSETS + "(listfile)").reader(4096);
// }
//}
Node<Node, Object, Actor> root = new BaseNode(new VisLabel("root"));
final boolean checkExisting = options_checkExisting.isChecked();
String fileName;
while ((fileName = reader.readLine()) != null) {
if (checkExisting && !Riiablo.mpqs.contains(fileName)) {
continue;
}
String path = FilenameUtils.getPathNoEndSeparator(fileName).toLowerCase();
treeify(fileTreeNodes, root, path);
final MPQFileHandle handle = (MPQFileHandle) Riiablo.mpqs.resolve(fileName);
VisLabel label = new VisLabel(FilenameUtils.getName(fileName));
final Node node = new BaseNode(label);
node.setValue(handle);
label.addListener(new ClickListener(Input.Buttons.RIGHT) {
@Override
public void clicked(InputEvent event, float x, float y) {
showPopmenu(node, handle);
}
});
String key = fileName.toLowerCase();
fileTreeNodes.put(key, node);
if (FilenameUtils.isExtension(key, "cof")) {
key = FilenameUtils.getBaseName(key);
fileTreeCofNodes.put(key, node);
}
if (path.isEmpty()) {
root.add(node);
} else {
fileTreeNodes.get(path + "\\").add(node);
}
}
sort(root);
fileTree.clearChildren();
for (Node child : root.getChildren()) {
fileTree.add(child);
}
fileTree.layout();
fileTreeFilter.clearText();
} catch (IOException e) {
throw new GdxRuntimeException("Failed to read list file.", e);
} finally {
StreamUtils.closeQuietly(reader);
}
}
@Test
public void file_name_url_apache() {
String fullFileName = FilenameUtils.getName(IMAGE_URL);
assertEquals("logo11w.png", fullFileName.toString());
}
/**
* Utility method to load a network file from resource directory without calling
* @param filePath path of the file relative to resources directory
* @return imported network
*/
private static Network loadNetworkFromResourceFile(String filePath) {
ReadOnlyDataSource dataSource = new ResourceDataSource(FilenameUtils.getBaseName(filePath), new ResourceSet(FilenameUtils.getPath(filePath), FilenameUtils.getName(filePath)));
return new UcteImporter().importData(dataSource, NetworkFactory.findDefault(), null);
}