org.apache.commons.io.FilenameUtils#getName ( )源码实例Demo

下面列出了org.apache.commons.io.FilenameUtils#getName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: TranskribusCore   文件: LocalDocWriter.java
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);
}
 
源代码2 项目: swagger   文件: SwaggerMappingSupport.java
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);
    }
}
 
源代码3 项目: smart-framework   文件: WebUtil.java
/**
 * 下载文件
 */
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);
    }
}
 
源代码4 项目: hsac-fitnesse-fixtures   文件: SeleniumHelper.java
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;
}
 
源代码5 项目: webanno   文件: LegacyRemoteApiController.java
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);
}
 
源代码6 项目: bbs   文件: FileUtil.java
/**
 *  获取文件名,含后缀
 * @param path 
 */
public static String getName(String path){
	if(path != null && !"".equals(path.trim())){
		return FilenameUtils.getName(path);
	}
	return "";
	
}
 
源代码7 项目: oim-fx   文件: HttpConnectionUtil.java
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;
  }
}
 
源代码8 项目: TranskribusCore   文件: LocalDocWriter.java
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);
}
 
源代码9 项目: sakai   文件: FileItemDataSource.java
@Override
public String getName() {
    String fileName = fileItem.getName();
    if (fileName != null) {
        fileName = FilenameUtils.getName(fileName);
    }
    return fileName;
}
 
源代码10 项目: 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));
}
 
源代码11 项目: incubator-retired-wave   文件: AttachmentServlet.java
@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]);
}
 
源代码13 项目: atlas   文件: BetterZip.java
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);
    }
 
源代码14 项目: xds-ide   文件: XdsPluginUpdater.java
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$
}
 
源代码15 项目: o2oa   文件: ActionUpdateContentCallback.java
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;
	}
}
 
源代码16 项目: piper   文件: S3ListObjects.java
public String getSuffix () {
  return FilenameUtils.getName(getKey());
}
 
源代码17 项目: streaming-file-server   文件: FileService.java
private static String filename(final Path path) {
  return FilenameUtils.getName(string(path));
}
 
源代码18 项目: riiablo   文件: MPQViewer.java
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);
  }
}
 
源代码19 项目: levelup-java-examples   文件: GetFileNameFromURL.java
@Test
public void file_name_url_apache() {

	String fullFileName = FilenameUtils.getName(IMAGE_URL);

	assertEquals("logo11w.png", fullFileName.toString());
}
 
源代码20 项目: powsybl-core   文件: UcteExporterTest.java
/**
 * 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);
}