List of usage examples for java.io File length
public long length()
From source file:com.ssn.listener.SSNHiveAlbumSelectionListner.java
private static void listFiles(File folder) { for (final File fileEntry : folder.listFiles()) { if (fileEntry.isFile()) { if (fileEntry.length() > 0) { iT++;/*from w w w .ja va 2 s. c o m*/ } } else if (fileEntry.isDirectory()) { dT++; listFiles(fileEntry); } } }
From source file:com.turn.ttorrent.common.TorrentCreator.java
/** * Return the concatenation of the SHA-1 hashes of a file's pieces. * * <p>//from w w w .j a v a2 s. c om * Hashes the given file piece by piece using the default Torrent piece * length (see {@link #PIECE_LENGTH}) and returns the concatenation of * these hashes, as a string. * </p> * * <p> * This is used for creating Torrent meta-info structures from a file. * </p> * * @param file The file to hash. */ public /* for testing */ static byte[] hashFiles(Executor executor, List<File> files, long nbytes, int pieceLength) throws InterruptedException, IOException { int npieces = (int) Math.ceil((double) nbytes / pieceLength); byte[] out = new byte[Torrent.PIECE_HASH_SIZE * npieces]; CountDownLatch latch = new CountDownLatch(npieces); ByteBuffer buffer = ByteBuffer.allocate(pieceLength); long start = System.nanoTime(); int piece = 0; for (File file : files) { logger.info("Hashing data from {} ({} pieces)...", new Object[] { file.getName(), (int) Math.ceil((double) file.length() / pieceLength) }); FileInputStream fis = FileUtils.openInputStream(file); FileChannel channel = fis.getChannel(); int step = 10; try { while (channel.read(buffer) > 0) { if (buffer.remaining() == 0) { buffer.flip(); executor.execute(new ChunkHasher(out, piece, latch, buffer)); buffer = ByteBuffer.allocate(pieceLength); piece++; } if (channel.position() / (double) channel.size() * 100f > step) { logger.info(" ... {}% complete", step); step += 10; } } } finally { channel.close(); fis.close(); } } // Hash the last bit, if any if (buffer.position() > 0) { buffer.flip(); executor.execute(new ChunkHasher(out, piece, latch, buffer)); piece++; } // Wait for hashing tasks to complete. latch.await(); long elapsed = System.nanoTime() - start; logger.info("Hashed {} file(s) ({} bytes) in {} pieces ({} expected) in {}ms.", new Object[] { files.size(), nbytes, piece, npieces, String.format("%.1f", elapsed / 1e6) }); return out; }
From source file:eu.eubrazilcc.lvl.storage.DatasetCollectionTest.java
private static void checkDataset(final Dataset dataset, final File file, final String namespace, final String filename, final Metadata metadata) { assertThat("lenght type coincides with expected", dataset.getLength(), equalTo(file.length())); assertThat("content type coincides with expected", dataset.getContentType(), equalTo(mimeType(file))); assertThat("filename coincides with expected", dataset.getFilename(), equalTo(isNotBlank(filename) ? filename : file.getName())); assertThat("namespace coincides with expected", dataset.getNamespace(), equalTo(namespace)); assertThat("metadata coincides with expected", dataset.getMetadata(), equalTo(metadata)); }
From source file:com.flurry.proguard.UploadProGuardMapping.java
/** * Upload the archive to Flurry/*from w w w.j a va 2s. c om*/ * * @param file the archive to send * @param projectId the project's id * @param uploadId the the upload's id * @param token the Flurry auth token */ private static void sendToUploadService(File file, String projectId, String uploadId, String token) { String uploadServiceUrl = String.format("%s/upload/%s/%s", UPLOAD_BASE, projectId, uploadId); List<Header> requestHeaders = getUploadServiceHeaders(file.length(), token); HttpPost postRequest = new HttpPost(uploadServiceUrl); postRequest.setEntity(new FileEntity(file)); HttpResponse response = executeHttpRequest(postRequest, requestHeaders); expectStatus(response, HttpURLConnection.HTTP_CREATED, HttpURLConnection.HTTP_ACCEPTED); }
From source file:com.modelon.oslc.adapter.fmi.integration.FMUConnector.java
public static List<FMU> loadFMUsFromDir(String fmuInterfaceCMDPath, String dir, String unzipTempDir) throws IOException { File[] fmuFiles = finder(dir, ".fmu"); if (fmuFiles == null) { throw new IOException(dir + " does not exist!"); }/*from w ww . j a v a 2 s. c om*/ List<FMU> discoveredFMUs = new ArrayList<>(); int index = 0; int numOfFMUFile = fmuFiles.length; System.out.println("\nFound " + numOfFMUFile + " FMUs in " + dir + "*.fmu \n"); for (File fmuFile : fmuFiles) { index++; System.out.println("FMU file (" + index + "/" + numOfFMUFile + "): " + fmuFile.getPath() + " (" + readableFileSize(fmuFile.length()) + ")"); try { FMU fmu = FMUConnector.loadSingleFMU(fmuInterfaceCMDPath, fmuFile.getPath(), unzipTempDir); if (fmu != null) { discoveredFMUs.add(fmu); System.out.println("\tPublishable?: Yes "); } else { System.out.println("\tPublishable?: No "); } System.out.println(""); } catch (NullPointerException e) { throw new IOException(fmuInterfaceCMDPath + " or " + fmuFile.getPath() + " or " + unzipTempDir + " does not exist;"); } } System.out.println("Total: " + numOfFMUFile + ", Publishable: " + discoveredFMUs.size() + "\n"); return discoveredFMUs; }
From source file:net.sf.firemox.tools.Picture.java
/** * Download a file from the specified URL to the specified local file. * //from ww w . j a v a 2 s . c o m * @param localFile * is the new card's picture to try first * @param remoteFile * is the URL where this picture will be downloaded in case of the * specified card name has not been found locally. * @param listener * the component waiting for this picture. * @since 0.83 Empty file are deleted to force file to be downloaded. */ public static synchronized void download(String localFile, URL remoteFile, MonitoredCheckContent listener) { BufferedOutputStream out = null; BufferedInputStream in = null; File toDownload = new File(localFile); if (toDownload.exists() && toDownload.length() == 0 && toDownload.canWrite()) { toDownload.delete(); } if (!toDownload.exists() || (toDownload.length() == 0 && toDownload.canWrite())) { // the file has to be downloaded try { if ("file".equals(remoteFile.getProtocol())) { File localRemoteFile = MToolKit .getFile(remoteFile.toString().substring(7).replaceAll("%20", " "), false); int contentLength = (int) localRemoteFile.length(); Log.info("Copying from " + localRemoteFile.getAbsolutePath()); LoaderConsole.beginTask( LanguageManager.getString("downloading") + " " + localRemoteFile.getAbsolutePath() + "(" + FileUtils.byteCountToDisplaySize(contentLength) + ")"); // Copy file in = new BufferedInputStream(new FileInputStream(localRemoteFile)); byte[] buf = new byte[2048]; int currentLength = 0; boolean succeed = false; for (int bufferLen = in.read(buf); bufferLen >= 0; bufferLen = in.read(buf)) { if (!succeed) { toDownload.getParentFile().mkdirs(); out = new BufferedOutputStream(new FileOutputStream(localFile)); succeed = true; } currentLength += bufferLen; if (out != null) { out.write(buf, 0, bufferLen); } if (listener != null) { listener.updateProgress(contentLength, currentLength); } } // Step 3: close streams IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); in = null; out = null; return; } // Testing mode? if (!MagicUIComponents.isUILoaded()) { return; } // Step 1: open streams final URLConnection connection = MToolKit.getHttpConnection(remoteFile); int contentLength = connection.getContentLength(); in = new BufferedInputStream(connection.getInputStream()); Log.info("Download from " + remoteFile + "(" + FileUtils.byteCountToDisplaySize(contentLength) + ")"); LoaderConsole.beginTask(LanguageManager.getString("downloading") + " " + remoteFile + "(" + FileUtils.byteCountToDisplaySize(contentLength) + ")"); // Step 2: read and write until done byte[] buf = new byte[2048]; int currentLength = 0; boolean succeed = false; for (int bufferLen = in.read(buf); bufferLen >= 0; bufferLen = in.read(buf)) { if (!succeed) { toDownload.getParentFile().mkdirs(); out = new BufferedOutputStream(new FileOutputStream(localFile)); succeed = true; } currentLength += bufferLen; if (out != null) { out.write(buf, 0, bufferLen); } if (listener != null) { listener.updateProgress(contentLength, currentLength); } } // Step 3: close streams IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); in = null; out = null; return; } catch (IOException e1) { if (MToolKit.getFile(localFile) != null) { MToolKit.getFile(localFile).delete(); } if (remoteFile.getFile().equals(remoteFile.getFile().toLowerCase())) { Log.fatal("could not load picture " + localFile + " from URL " + remoteFile + ", " + e1.getMessage()); } String tmpRemote = remoteFile.toString().toLowerCase(); try { download(localFile, new URL(tmpRemote), listener); } catch (MalformedURLException e) { Log.fatal("could not load picture " + localFile + " from URL " + tmpRemote + ", " + e.getMessage()); } } } }
From source file:arena.utils.FileUtils.java
public static void gzip(File input, File outFile) { Log log = LogFactory.getLog(FileUtils.class); InputStream inStream = null;//from w w w . j av a2s. c o m OutputStream outStream = null; GZIPOutputStream gzip = null; try { long inFileLengthKB = input.length() / 1024L; // Open the out file if (outFile == null) { outFile = new File(input.getParentFile(), input.getName() + ".gz"); } inStream = new FileInputStream(input); outStream = new FileOutputStream(outFile, true); gzip = new GZIPOutputStream(outStream); // Iterate through in buffers and write out to the gzipped output stream byte buffer[] = new byte[102400]; // 100k buffer int read = 0; long readSoFar = 0; while ((read = inStream.read(buffer)) != -1) { readSoFar += read; gzip.write(buffer, 0, read); log.debug("Gzipped " + (readSoFar / 1024L) + "KB / " + inFileLengthKB + "KB of logfile " + input.getName()); } // Close the streams inStream.close(); inStream = null; gzip.close(); gzip = null; outStream.close(); outStream = null; // Delete the old file input.delete(); log.debug("Gzip of logfile " + input.getName() + " complete"); } catch (IOException err) { // Delete the gzip file log.error("Error during gzip of logfile " + input, err); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException err2) { } } if (gzip != null) { try { gzip.close(); } catch (IOException err2) { } } if (outStream != null) { try { outStream.close(); } catch (IOException err2) { } } } }
From source file:edu.ku.brc.specify.tools.AppendHelp.java
@SuppressWarnings("unchecked") static public String getContents(final File file, final String target, final String anchor) throws IOException { if (file.length() < 500) { return ""; }/*from w ww . j a v a 2s . c om*/ StringBuilder sb = new StringBuilder(); String contents = FileUtils.readFileToString(file); String lower = contents.toLowerCase(); int sInx = lower.indexOf("<title>"); int eInx = lower.indexOf("</title>"); //String title = contents.substring(sInx+8, eInx-1); sInx = lower.indexOf("<body"); sInx = lower.indexOf('>', sInx); eInx = lower.indexOf("</body>"); if (eInx == -1) { eInx = lower.indexOf("</html>"); } if (sInx == -1 || eInx == -1) { System.out.println(file.getAbsolutePath() + " " + sInx + " " + eInx); return ""; } String body = contents.substring(sInx + 1, eInx - 1); body = StringUtils.replace(body, "src=\"../images", "src=\"help/SpecifyHelp/images"); body = StringUtils.replace(body, "src=\"../../images", "src=\"help/images"); body = StringUtils.replace(body, "background=\"../../images", "background=\"help/images"); if (contents.indexOf("topbar.png") == -1) { sb.append("<HR>"); } sb.append("<a name=\""); sb.append(anchor != null ? anchor : target); sb.append("\">"); sb.append(body); return sb.toString(); }
From source file:com.joyent.manta.client.crypto.EncryptingEntityTest.java
private static void verifyEncryptionWorksRoundTrip(byte[] keyBytes, SupportedCipherDetails cipherDetails, HttpEntity entity, Predicate<byte[]> validator) throws Exception { SecretKey key = SecretKeyUtils.loadKey(keyBytes, cipherDetails); EncryptingEntity encryptingEntity = new EncryptingEntity(key, cipherDetails, entity); File file = File.createTempFile("ciphertext-", ".data"); FileUtils.forceDeleteOnExit(file);// w ww .ja v a2s . c o m try (FileOutputStream out = new FileOutputStream(file)) { encryptingEntity.writeTo(out); } Assert.assertEquals(file.length(), encryptingEntity.getContentLength(), "Expected ciphertext file size doesn't match actual file size " + "[originalContentLength=" + entity.getContentLength() + "] -"); byte[] iv = encryptingEntity.getCipher().getIV(); Cipher cipher = cipherDetails.getCipher(); cipher.init(Cipher.DECRYPT_MODE, key, cipherDetails.getEncryptionParameterSpec(iv)); final long ciphertextSize; if (cipherDetails.isAEADCipher()) { ciphertextSize = encryptingEntity.getContentLength(); } else { ciphertextSize = encryptingEntity.getContentLength() - cipherDetails.getAuthenticationTagOrHmacLengthInBytes(); } try (FileInputStream in = new FileInputStream(file); BoundedInputStream bin = new BoundedInputStream(in, ciphertextSize); CipherInputStream cin = new CipherInputStream(bin, cipher)) { final byte[] actualBytes = IOUtils.toByteArray(cin); final byte[] hmacBytes = new byte[cipherDetails.getAuthenticationTagOrHmacLengthInBytes()]; in.read(hmacBytes); Assert.assertTrue(validator.test(actualBytes), "Entity validation failed"); } }
From source file:com.almarsoft.GroundhogReader.lib.FSUtils.java
public static String loadStringFromDiskFile(String fullPath, boolean existenceChecked) throws UsenetReaderException, IOException { String ret = null;/*from w ww.j a v a2 s . co m*/ File f = new File(fullPath); if (!existenceChecked && !f.exists()) { throw new UsenetReaderException("File could not be found in " + fullPath); } char[] buff = new char[(int) f.length()]; BufferedReader in = null; try { FileReader freader = new FileReader(fullPath); in = new BufferedReader(freader); in.read(buff); ret = new String(buff); } finally { if (in != null) in.close(); } return ret; }