List of usage examples for java.nio.file Files size
public static long size(Path path) throws IOException
From source file:io.undertow.servlet.test.proprietry.TransferTestCase.java
@Test public void testServletRequest() throws Exception { TestListener.init(2);//from w w w. ja v a2s .com TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/aa"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); final byte[] response = HttpClientUtils.readRawResponse(result); Path file = Paths.get(TXServlet.class.getResource(TXServlet.class.getSimpleName() + ".class").toURI()); byte[] expected = new byte[(int) Files.size(file)]; DataInputStream dataInputStream = new DataInputStream(Files.newInputStream(file)); dataInputStream.readFully(expected); dataInputStream.close(); Assert.assertArrayEquals(expected, response); } finally { client.getConnectionManager().shutdown(); } }
From source file:com.nartex.RichFileManager.java
@Override public void preview(HttpServletRequest request, HttpServletResponse resp) { Path file = this.documentRoot.resolve(cleanPreview(this.get.get("path"))); boolean thumbnail = false; String paramThumbs = request.getParameter("thumbnail"); if (paramThumbs != null && paramThumbs.equals("true")) { thumbnail = true;//w ww. j a va 2s .co m } long size = 0; try { size = Files.size(file); } catch (IOException e) { this.error(sprintf(lang("INVALID_DIRECTORY_OR_FILE"), file.toFile().getName())); } if (this.get.get("path") != null && Files.exists(file)) { resp.setHeader("Content-type", "image/" + getFileExtension(file.toFile().getName())); // octet-stream" + getFileExtension(file.toFile().getName())); resp.setHeader("Content-Transfer-Encoding", "Binary"); resp.setHeader("Content-length", "" + size); resp.setHeader("Content-Disposition", "inline; filename=\"" + getFileBaseName(file.toFile().getName()) + "\""); // handle caching resp.setHeader("Pragma", "no-cache"); resp.setHeader("Expires", "0"); resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); readSmallFile(resp, file); } else { error(sprintf(lang("FILE_DOES_NOT_EXIST"), this.get.get("path"))); } }
From source file:de.ks.file.FileStore.java
private long getFileSize(File file) { try {// ww w .jav a 2 s. c o m return Files.size(file.toPath()); } catch (IOException e) { log.error("Could not get filesize from {}", file, e); return -1; } }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.tests.integration.HtmlToMobiConverterTest.java
@Test public void testConvertToMobi() throws Exception { logger.debug("testConvertToMobi"); mobi = this.htmlToMobiConverter.convertToMobi(inputFile.toFile()); assertNotNull(mobi);//from w w w . j a v a 2 s .co m logger.debug("Output file created at " + mobi.toPath().toAbsolutePath().toString()); assertTrue(Files.exists(mobi.toPath())); assertTrue(Files.size(mobi.toPath()) > 0L); }
From source file:org.savantbuild.io.tar.TarTools.java
/** * Untars a TAR file. This also handles tar.gz files by checking the file extension. If the file extension ends in .gz * it will read the tarball through a GZIPInputStream. * * @param file The TAR file.//from w ww . j a va 2 s. c o m * @param to The directory to untar to. * @param useGroup Determines if the group name in the archive is used. * @param useOwner Determines if the owner name in the archive is used. * @throws IOException If the untar fails. */ public static void untar(Path file, Path to, boolean useGroup, boolean useOwner) throws IOException { if (Files.notExists(to)) { Files.createDirectories(to); } InputStream is = Files.newInputStream(file); if (file.toString().endsWith(".gz")) { is = new GZIPInputStream(is); } try (TarArchiveInputStream tis = new TarArchiveInputStream(is)) { TarArchiveEntry entry; while ((entry = tis.getNextTarEntry()) != null) { Path entryPath = to.resolve(entry.getName()); if (entry.isDirectory()) { // Skip directory entries that don't add any value if (entry.getMode() == 0 && entry.getGroupName() == null && entry.getUserName() == null) { continue; } if (Files.notExists(entryPath)) { Files.createDirectories(entryPath); } if (entry.getMode() != 0) { Set<PosixFilePermission> permissions = FileTools.toPosixPermissions(entry.getMode()); Files.setPosixFilePermissions(entryPath, permissions); } if (useGroup && entry.getGroupName() != null && !entry.getGroupName().trim().isEmpty()) { GroupPrincipal group = FileSystems.getDefault().getUserPrincipalLookupService() .lookupPrincipalByGroupName(entry.getGroupName()); Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setGroup(group); } if (useOwner && entry.getUserName() != null && !entry.getUserName().trim().isEmpty()) { UserPrincipal user = FileSystems.getDefault().getUserPrincipalLookupService() .lookupPrincipalByName(entry.getUserName()); Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setOwner(user); } } else { if (Files.notExists(entryPath.getParent())) { Files.createDirectories(entryPath.getParent()); } if (Files.isRegularFile(entryPath)) { if (Files.size(entryPath) == entry.getSize()) { continue; } else { Files.delete(entryPath); } } Files.createFile(entryPath); try (OutputStream os = Files.newOutputStream(entryPath)) { byte[] ba = new byte[1024]; int read; while ((read = tis.read(ba)) != -1) { if (read > 0) { os.write(ba, 0, read); } } } if (entry.getMode() != 0) { Set<PosixFilePermission> permissions = FileTools.toPosixPermissions(entry.getMode()); Files.setPosixFilePermissions(entryPath, permissions); } if (useGroup && entry.getGroupName() != null && !entry.getGroupName().trim().isEmpty()) { GroupPrincipal group = FileSystems.getDefault().getUserPrincipalLookupService() .lookupPrincipalByGroupName(entry.getGroupName()); Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setGroup(group); } if (useOwner && entry.getUserName() != null && !entry.getUserName().trim().isEmpty()) { UserPrincipal user = FileSystems.getDefault().getUserPrincipalLookupService() .lookupPrincipalByName(entry.getUserName()); Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setOwner(user); } } } } }
From source file:org.n52.geolabel.formats.PngTest.java
@Test public void sizeParameterIsUsed() throws IOException { Label l1 = new Label(); InputStream inSmall = this.encoder.encode(l1, 64); Label l2 = new Label(); InputStream inLarge = this.encoder.encode(l2, 512); File tempSmall = File.createTempFile("geolabel_", ".png"); try (FileOutputStream tempFileSmall = new FileOutputStream(tempSmall);) { IOUtils.copy(inSmall, tempFileSmall); }/*from w ww .j a v a2s . c o m*/ File tempLarge = File.createTempFile("geolabel_", ".png"); try (FileOutputStream tempFileLarge = new FileOutputStream(tempLarge);) { IOUtils.copy(inLarge, tempFileLarge); } // System.out.printf("Saved small and larg geolabel as %s and %s", // tempSmall.getAbsolutePath(), // tempLarge.getAbsolutePath()); Long small = Long.valueOf(Files.size(tempSmall.toPath())); Long large = Long.valueOf(Files.size(tempLarge.toPath())); assertThat("file size of larger label is larger", large, is(greaterThan(small))); tempSmall.deleteOnExit(); tempLarge.deleteOnExit(); }
From source file:com.sastix.cms.server.utils.MultipartFileSender.java
public void serveResource() throws Exception { if (response == null || request == null) { return;/*from w ww. ja v a2 s. c o m*/ } Long length = Files.size(filepath); String fileName = filepath.getFileName().toString(); FileTime lastModifiedObj = Files.getLastModifiedTime(filepath); if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } long lastModified = LocalDateTime .ofInstant(lastModifiedObj.toInstant(), ZoneId.of(ZoneOffset.systemDefault().getId())) .toEpochSecond(ZoneOffset.UTC); // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && HttpUtils.matches(ifNoneMatch, fileName)) { response.setHeader("ETag", fileName); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setHeader("ETag", fileName); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !HttpUtils.matches(ifMatch, fileName)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(fileName)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100). long start = Range.sublong(part, 0, part.indexOf("-")); long end = Range.sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and set content disposition. String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } else if (!contentType.startsWith("image")) { // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. String accept = request.getHeader("Accept"); disposition = accept != null && HttpUtils.accepts(accept, contentType) ? "inline" : "attachment"; } LOG.debug("Content-Type : {}", contentType); // Initialize response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Type", contentType); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); LOG.debug("Content-Disposition : {}", disposition); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", fileName); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. try (InputStream input = new BufferedInputStream(Files.newInputStream(filepath)); OutputStream output = response.getOutputStream()) { if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. LOG.debug("Return full file"); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + full.start + "-" + full.end + "/" + full.total); response.setHeader("Content-Length", String.valueOf(full.length)); Range.copy(input, output, length, full.start, full.length); } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); LOG.debug("Return 1 part of file : from ({}) to ({})", r.start, r.end); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. // Copy single part range. Range.copy(input, output, length, r.start, r.length); } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. // Cast back to ServletOutputStream to get the easy println methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { LOG.debug("Return multi part of file : from ({}) to ({})", r.start, r.end); // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. Range.copy(input, output, length, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } }
From source file:org.wso2.carbon.apimgt.hybrid.gateway.usage.publisher.tasks.APIUsageFileUploadTask.java
@Override public void execute() { log.info("Running API Usage File Upload Task."); try {/*ww w . j av a 2s . c om*/ configManager = ConfigManager.getConfigManager(); } catch (OnPremiseGatewayException e) { log.error("Error occurred while reading the configuration. Usage upload was cancelled.", e); return; } //[CARBON_HOME]/api-usage-data/ Path usageFileDirectory = Paths.get(CarbonUtils.getCarbonHome(), MicroGatewayAPIUsageConstants.API_USAGE_OUTPUT_DIRECTORY); //Rotate current file Path activeFilePath = Paths.get(usageFileDirectory.toString(), MicroGatewayAPIUsageConstants.API_USAGE_OUTPUT_FILE_NAME); try { if (Files.size(activeFilePath) > 0) { //Don't rotate if the current file is empty if (log.isDebugEnabled()) { log.debug("Rotating current file for uploading."); } UsageFileWriter.getInstance().rotateFile(activeFilePath.toString()); } } catch (UsagePublisherException | IOException e) { log.error("Error occurred while rotating the current file. Will only upload the previously " + "rotated files."); } File[] listOfFiles = new File(usageFileDirectory.toUri()).listFiles(); if (listOfFiles != null) { Arrays.sort(listOfFiles); for (File file : listOfFiles) { String fileName = file.getName(); //Only get the files which have been rotated if (fileName.endsWith(MicroGatewayAPIUsageConstants.ZIP_EXTENSION)) { try { boolean uploadStatus = uploadCompressedFile(file.toPath(), fileName); if (uploadStatus) { //Rename the file to mark as uploaded Path renamedPath = Paths.get( file.getAbsolutePath() + MicroGatewayAPIUsageConstants.UPLOADED_FILE_SUFFIX); Files.move(file.toPath(), renamedPath); } else { log.error("Usage file Upload failed. It will be retried in the next task run."); } } catch (IOException e) { log.error("Error occurred while moving the uploaded the File : " + fileName, e); } } } } }
From source file:ec.edu.chyc.manejopersonal.managebean.GestorTesis.java
private void cargarDatosTesis(Long id) { tesis = tesisController.findTesis(id); listaProyectos = new ArrayList<>(tesis.getProyectosCollection()); listaCodirectores = new ArrayList<>(tesis.getCodirectoresCollection()); listaTutores = new ArrayList<>(tesis.getTutoresCollection()); listaAutoresTesis = new ArrayList<>(tesis.getAutoresCollection()); try {/*from www.j a va2 s . c o m*/ Path pathArchivoSubido = ServerUtils.getPathActasAprobacionTesis() .resolve(tesis.getArchivoActaAprobacion()); if (Files.isRegularFile(pathArchivoSubido) && Files.exists(pathArchivoSubido)) { Long size = Files.size(pathArchivoSubido); tamanoArchivo = ServerUtils.humanReadableByteCount(size); } else { tamanoArchivo = ""; } } catch (IOException ex) { Logger.getLogger(GestorContrato.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.fim.internal.hash.FileHasherPerformanceTest.java
@Test public void hashFiles() throws IOException { long start = System.currentTimeMillis(); List<FileHash> allHash = new ArrayList(); for (int fileCount = 0; fileCount < TOTAL_FILE_CONT; fileCount++) { Path fileToHash = context.getRepositoryRootDir().resolve("file_" + fileCount); allHash.add(cut.hashFile(fileToHash, Files.size(fileToHash))); }/*from ww w. j a v a2s. com*/ long duration = System.currentTimeMillis() - start; System.out.println("Took: " + DurationFormatUtils.formatDuration(duration, "HH:mm:ss")); System.out.println("Total bytes hash=" + FileUtils.byteCountToDisplaySize(cut.getTotalBytesHashed())); }