Java Code Examples for java.nio.file.Files#probeContentType()
The following examples show how to use
java.nio.file.Files#probeContentType() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ContentTypeUtil.java From spring-boot-plus with Apache License 2.0 | 6 votes |
/** * 获取文件内容类型 * @param file * @return */ public static String getContentType(File file){ if (file == null){ return null; } Path path = Paths.get(file.toURI()); if (path == null){ return null; } String contentType = null; try { contentType = Files.probeContentType(path); } catch (IOException e) { log.error("获取文件ContentType异常",e); } if (contentType == null){ // 读取拓展的自定义配置 contentType = getContentTypeByExtension(file); } // 设置默认的内容类型 if (contentType == null){ contentType = DEFAULT_MIME_TYPE; } return contentType; }
Example 2
Source File: ImageCommandBase.java From SkyBot with GNU Affero General Public License v3.0 | 6 votes |
@Nullable private String tryGetAttachment(CommandContext ctx) { final Attachment attachment = ctx.getMessage().getAttachments().get(0); final File file = new File(attachment.getFileName()); String mimetype = null; try { mimetype = Files.probeContentType(file.toPath()); } catch (IOException e) { e.printStackTrace(); } //mimetype should be something like "image/png" if (mimetype == null || !mimetype.split("/")[0].equals("image")) { sendMsg(ctx, "That file does not look like an image"); return null; } return attachment.getUrl(); }
Example 3
Source File: RequestFormFilesExtractor.java From AuTe-Framework with Apache License 2.0 | 6 votes |
private Attachment mapDataToAttachment(File resultDirectory, StepResult stepResult, FormData formData) { String extension = FilenameUtils.getExtension(formData.getFilePath()); String relativePath = getAttachRelativePath(formData.getFieldName(), extension); Path sourcePath = Paths.get(projectRepositoryPath, stepResult.getProjectCode(), formData.getFilePath()); Path attachPath = resultDirectory.toPath().resolve(relativePath); String contentType; try { contentType = Files.probeContentType(sourcePath); } catch (IOException ignored) { contentType = TEXT_PLAIN; } try { Files.copy(sourcePath, attachPath); } catch (IOException e) { log.warn("Exception while copying form data file: {}", formData.getFilePath(), e); } return new Attachment().withTitle(formData.getFieldName()).withSource(relativePath).withType(contentType); }
Example 4
Source File: File.java From webdsl with Apache License 2.0 | 6 votes |
public static File createFromFilePath(String fullPath) { File file = null; try { java.io.File fileOnDisk = new java.io.File(fullPath); if(!fileOnDisk.exists()) { return null; } else { file = new utils.File(); file.setContentStream(new FileInputStream(fileOnDisk)); String contentType = Files.probeContentType( fileOnDisk.toPath() ); file.setContentType(contentType); file.setFileName( fileOnDisk.getName() ); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return file; }
Example 5
Source File: FrontendLoader.java From elepy with Apache License 2.0 | 6 votes |
private void setupLogo(ElepyPostConfiguration elepy, HttpService http) throws IOException { final var logo = Optional.ofNullable(elepy.getPropertyConfig().getString("cms.logo")).orElse("/banner.jpg"); final var logoURI = Optional.ofNullable(getClass().getResource(logo)).orElseThrow(() -> new ElepyConfigException(logo + " can't be found")); final var logoContentType = Files.probeContentType(Paths.get(logoURI.getPath())); final var input = Objects.requireNonNull(getClass().getResourceAsStream(logo)); final var logoBytes = IOUtils.toByteArray(input); http.get("/elepy/logo", ctx -> { if (logo.startsWith("http://") || logo.startsWith("https://")) { ctx.redirect(logo); } else { ctx.type(logoContentType); ctx.response().result(logoBytes); } }); }
Example 6
Source File: DarkFileChooserUI.java From darklaf with MIT License | 5 votes |
public Icon getIcon(final File f) { Icon icon = getCachedIcon(f); if (icon != null) { return icon; } icon = fileIcon; if (f != null) { FileSystemView fsv = getFileChooser().getFileSystemView(); if (fsv.isFloppyDrive(f)) { icon = floppyDriveIcon; } else if (fsv.isDrive(f)) { icon = hardDriveIcon; } else if (fsv.isComputerNode(f)) { icon = computerIcon; } else if (f.isDirectory()) { icon = directoryIcon; } else { try { String mimeType = Files.probeContentType(f.toPath()); if (mimeType == null) mimeType = ""; if (mimeType.startsWith(MIME_IMAGE)) { icon = imageFileIcon; } else if (mimeType.startsWith(MIME_TEXT)) { icon = textFileIcon; } } catch (IOException e) { e.printStackTrace(); } } } cacheIcon(f, icon); return icon; }
Example 7
Source File: Utils.java From signal-cli with GNU General Public License v3.0 | 5 votes |
private static String getFileMimeType(File file) throws IOException { String mime = Files.probeContentType(file.toPath()); if (mime == null) { try (InputStream bufferedStream = new BufferedInputStream(new FileInputStream(file))) { mime = URLConnection.guessContentTypeFromStream(bufferedStream); } } if (mime == null) { mime = "application/octet-stream"; } return mime; }
Example 8
Source File: TemporaryFileInputStream.java From wildfly-core with GNU Lesser General Public License v2.1 | 5 votes |
@Override public String getContentType() { String contentType; try { contentType = Files.probeContentType(file); if(contentType == null) { contentType = DEFAULT_CONTENT_TYPE; } } catch (IOException ex) { DeploymentRepositoryLogger.ROOT_LOGGER.debugf(ex, "Error obtaining content-type for %s", file.toString()); contentType = DEFAULT_CONTENT_TYPE; } return contentType; }
Example 9
Source File: MCRFileTypeDetector.java From mycore with GNU General Public License v3.0 | 5 votes |
@Override public String probeContentType(Path path) throws IOException { LOGGER.debug(() -> "Probing content type of: " + path); if (!(path.getFileSystem() instanceof MCRIFSFileSystem)) { return null; } MCRFilesystemNode resolvePath = MCRFileSystemProvider.resolvePath(MCRPath.toMCRPath(path)); if (resolvePath == null) { throw new NoSuchFileException(path.toString()); } if (resolvePath instanceof MCRDirectory) { throw new NoSuchFileException(path.toString()); } MCRFile file = (MCRFile) resolvePath; String mimeType = file.getContentType().getMimeType(); LOGGER.debug(() -> "IFS mime-type: " + mimeType); if (defaultMimeType.equals(mimeType)) { Path dummy = Paths.get(path.getFileName().toString()); String dummyType = Files.probeContentType(dummy); if (dummyType != null) { LOGGER.debug(() -> "System mime-type #1: " + dummyType); return dummyType; } String systemMimeType = Files.probeContentType(file.getLocalFile().toPath()); if (systemMimeType != null) { LOGGER.debug(() -> "System mime-type #2: " + systemMimeType); return systemMimeType; } } return mimeType; }
Example 10
Source File: UrlEndpoints.java From SB_Elsinore_Server with MIT License | 5 votes |
/** * Read the incoming parameters and update the name as appropriate. * @return True if success, false if failure */ @SuppressWarnings("unchecked") @UrlEndpoint(url = "/uploadimage", help = "Upload an image for the brewery logo", parameters = {@Parameter(name = "file", value = "Push a file to this EndPoint to upload")}) public Response updateBreweryImage() { final Map<String, String> files = this.files; if (files.size() == 1) { for (Map.Entry<String, String> entry : files.entrySet()) { try { File uploadedFile = new File(entry.getValue()); String fileType = Files.probeContentType( uploadedFile.toPath()); if (fileType.equalsIgnoreCase(MIME_TYPES.get("gif")) || fileType.equalsIgnoreCase(MIME_TYPES.get("jpg")) || fileType.equalsIgnoreCase(MIME_TYPES.get("jpeg")) || fileType.equalsIgnoreCase(MIME_TYPES.get("png"))) { File targetFile = new File(rootDir, "brewerImage.gif"); if (targetFile.exists() && !targetFile.delete()) { BrewServer.LOG.warning("Failed to delete " + targetFile.getCanonicalPath()); } LaunchControl.copyFile(uploadedFile, targetFile); if (!targetFile.setReadable(true, false) || targetFile.setWritable(true, false)) { BrewServer.LOG.warning("Failed to set read write permissions on " + targetFile.getCanonicalPath()); } LaunchControl.setFileOwner(targetFile); return new Response(Response.Status.OK, MIME_TYPES.get("text"), "Updated brewery logo"); } } catch (IOException e) {} } } return null; }
Example 11
Source File: Utils.java From signal-cli with GNU General Public License v3.0 | 5 votes |
static StreamDetails createStreamDetailsFromFile(File file) throws IOException { InputStream stream = new FileInputStream(file); final long size = file.length(); String mime = Files.probeContentType(file.toPath()); if (mime == null) { mime = "application/octet-stream"; } return new StreamDetails(stream, mime, size); }
Example 12
Source File: FSUtils.java From bamboobsc with Apache License 2.0 | 5 votes |
/** * get MIME-TYPE * Using javax.activation.MimetypesFileTypeMap * * @param file * @return * @throws Exception */ public static String getMimeType(File file) throws Exception { String mimeType=""; if (file==null || !file.exists() || file.isDirectory() ) { return mimeType; } /* mimeType=new MimetypesFileTypeMap().getContentType(file); return mimeType; */ return Files.probeContentType(file.toPath()); }
Example 13
Source File: FileReader.java From HtmlUnit-Android with Apache License 2.0 | 5 votes |
/** * Reads the contents of the specified {@link Blob} or {@link File}. * @param object the {@link Blob} or {@link File} from which to read * @throws IOException if an error occurs */ @JsxFunction public void readAsDataURL(final Object object) throws IOException { readyState_ = LOADING; final java.io.File file = ((File) object).getFile(); String contentType = Files.probeContentType(file.toPath()); try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { FileUtils.copyFile(file, bos); final byte[] bytes = bos.toByteArray(); final String value = new String(new Base64().encode(bytes)); final BrowserVersion browserVersion = getBrowserVersion(); result_ = "data:"; final boolean includeConentType = browserVersion.hasFeature(JS_FILEREADER_CONTENT_TYPE); if (!value.isEmpty() || includeConentType) { if (contentType == null) { if (includeConentType) { contentType = "application/octet-stream"; } else { contentType = ""; } } result_ += contentType + ";base64," + value; } if (value.isEmpty() && getBrowserVersion().hasFeature(JS_FILEREADER_EMPTY_NULL)) { result_ = "null"; } } readyState_ = DONE; final Event event = new Event(this, Event.TYPE_LOAD); fireEvent(event); }
Example 14
Source File: LocatorFileAccept.java From sparql-generate with Apache License 2.0 | 5 votes |
/** * Open anything that looks a bit like a file name */ @Override public TypedInputStream open(LookUpRequest request) { String filenameIRI = request.getFilenameOrURI(); if(filenameIRI.startsWith("http") || filenameIRI.startsWith("coap")) { return null; } String fn = toFileName(filenameIRI); if (fn == null) { log.debug("Cannot find a proper filename: " + filenameIRI); return null; } try { if (!exists$(fn)) { return null; } } catch (AccessControlException e) { log.debug("Security problem testing for file", e); return null; } try { InputStream in = IO.openFileEx(fn); try { String ct = Files.probeContentType(Paths.get(new File(filenameIRI).getName())); return new TypedInputStream(in, ContentType.create(ct), filenameIRI); } catch (Exception ex) { return new TypedInputStream(in, (ContentType) null, filenameIRI); } } catch (IOException ioEx) { // Includes FileNotFoundException // We already tested whether the file exists or not. log.debug("File unreadable (but exists): " + fn + " Exception: " + ioEx.getMessage()); return null; } }
Example 15
Source File: MimeTypeUnitTest.java From tutorials with MIT License | 5 votes |
/** * Test method, demonstrating usage in Java 7. * * @throws IOException */ @Test public void whenUsingJava7_thenSuccess() throws IOException { final Path path = new File(FILE_LOC).toPath(); final String mimeType = Files.probeContentType(path); assertEquals(mimeType, PNG_EXT); }
Example 16
Source File: MCRFileTypeDetector.java From mycore with GNU General Public License v3.0 | 5 votes |
@Override public String probeContentType(Path path) throws IOException { LOGGER.debug(() -> "Probing content type of: " + path); if (!(path.getFileSystem() instanceof MCRIFSFileSystem)) { return null; } MCRStoredNode resolvePath = MCRFileSystemUtils.resolvePath(MCRPath.toMCRPath(path)); if (resolvePath instanceof MCRDirectory) { throw new NoSuchFileException(path.toString()); } MCRFile file = (MCRFile) resolvePath; String mimeType = Files.probeContentType(file.getLocalPath()); LOGGER.debug(() -> "IFS mime-type: " + mimeType); return mimeType; }
Example 17
Source File: MCRWCMSFileBrowserResource.java From mycore with GNU General Public License v3.0 | 5 votes |
@GET @Path("/files") public String getFiles(@QueryParam("path") String path, @QueryParam("type") String type) throws IOException { File dir = new File(MCRWebPagesSynchronizer.getWCMSDataDir().getPath() + path); JsonObject jsonObj = new JsonObject(); JsonArray jsonArray = new JsonArray(); File[] fileArray = dir.listFiles(); if (fileArray != null) { for (File file : fileArray) { String mimetype = Files.probeContentType(file.toPath()); if (mimetype != null && (type.equals("images") ? mimetype.split("/")[0].equals("image") : !mimetype.split("/")[1].contains("xml"))) { JsonObject fileJsonObj = new JsonObject(); fileJsonObj.addProperty("name", file.getName()); fileJsonObj.addProperty("path", context.getContextPath() + path + "/" + file.getName()); if (file.isDirectory()) { fileJsonObj.addProperty("type", "folder"); } else { fileJsonObj.addProperty("type", mimetype.split("/")[0]); } jsonArray.add(fileJsonObj); } } jsonObj.add("files", jsonArray); return jsonObj.toString(); } return ""; }
Example 18
Source File: TestFiles.java From jsr203-hadoop with Apache License 2.0 | 4 votes |
@Test public void probeContentType() throws IOException { Path rootPath = Paths.get(clusterUri); Path path = Files.createTempFile(rootPath, "test", "tmp"); Files.probeContentType(path); }
Example 19
Source File: InstagramGenericUtil.java From instagram4j with Apache License 2.0 | 4 votes |
public static boolean isVideoFile(Path path) throws IOException { String mimeType = Files.probeContentType(path); return mimeType != null && mimeType.startsWith("video"); }
Example 20
Source File: MCRPathContent.java From mycore with GNU General Public License v3.0 | 4 votes |
@Override public String getMimeType() throws IOException { return mimeType == null ? Files.probeContentType(path) : mimeType; }