Java Code Examples for java.io.File#length()
The following examples show how to use
java.io.File#length() .
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: HeifReader.java From heifreader with MIT License | 6 votes |
/** * Decode a file path into a bitmap. * * @param pathName complete path name for the file to be decoded. * @return The decoded bitmap, or null if the image could not be decoded. */ public static Bitmap decodeFile(String pathName) { assertPrecondition(); try { File file = new File(pathName); long fileSize = file.length(); if (LIMIT_FILESIZE < fileSize) { Log.e(TAG, "file size exceeds limit(" + LIMIT_FILESIZE + ")"); return null; } byte[] data = new byte[(int) fileSize]; try (FileInputStream fis = new FileInputStream(file)) { fis.read(data); return decodeByteArray(data); } } catch (IOException ex) { Log.e(TAG, "decodeFile failure", ex); return null; } }
Example 2
Source File: AttachmentStorage.java From Onosendai with Apache License 2.0 | 6 votes |
public static void cleanTempOutputDir (final Context context) { final File dir = getBaseDir(context); long bytesFreed = 0L; if (dir.exists()) { final long now = System.currentTimeMillis(); for (final File f : dir.listFiles()) { if (now - f.lastModified() > C.TMP_SCALED_IMG_EXPIRY_MILLIS) { final long fLength = f.length(); if (f.delete()) { bytesFreed += fLength; } else { LOG.w("Failed to delete expired file: '%s'.", f.getAbsolutePath()); } } } } LOG.i("Freed %s bytes of temp attachment files.", bytesFreed); }
Example 3
Source File: IOUtil.java From gameserver with Apache License 2.0 | 6 votes |
/** * Read the file raw content into byte array. * @param fileName * @return */ public static final byte[] readFileBytes(File file) throws IOException { if ( file.exists() && file.isFile() ) { FileInputStream fis = new FileInputStream(file); int fileLen = (int)file.length(); byte[] buf = new byte[fileLen]; int len = 0; while ( len < fileLen ) { int n = fis.read(buf, len, fileLen-len); if ( n >= 0 ) { len += n; } else { break; } } return buf; } else { throw new IOException(file+" does not exist or is not file!"); } }
Example 4
Source File: CacheHelper.java From aptoide-client-v8 with GNU General Public License v3.0 | 5 votes |
/** * check if the ttl of the file was reached and delete it if it was */ private long removeFile(long timeToCache, long now, File file) { long deletedSize = 0; if ((now - file.lastModified()) > timeToCache) { long fileSize = file.length(); Logger.getInstance() .d(TAG, "removeFile: " + file.getAbsolutePath()); //update deleted size if file was deleted if (file.delete()) { deletedSize = fileSize; } } return deletedSize; }
Example 5
Source File: ProjectActivity.java From microbit with Apache License 2.0 | 5 votes |
private Project getLatestProjectFromFolder(long lengthOfSearchingFile) { File downloadDirectory = Environment.getExternalStoragePublicDirectory(Environment .DIRECTORY_DOWNLOADS); FilenameFilter hexFilenameFilter = new FilenameFilter() { @Override public boolean accept(File dir, String filename) { return filename.endsWith(".hex"); } }; File nowDownloadedFile = null; File downloadFiles[] = downloadDirectory.listFiles(hexFilenameFilter); if(downloadFiles != null) { for(File file : downloadFiles) { if(nowDownloadedFile == null) { if(file.length() == lengthOfSearchingFile) { nowDownloadedFile = file; } } else if(file.length() == lengthOfSearchingFile && file.lastModified() > nowDownloadedFile.lastModified ()) { nowDownloadedFile = file; } } } String fullPathOfFile; if(nowDownloadedFile == null) { Log.e(TAG, "Can't find file"); return null; } else { fullPathOfFile = nowDownloadedFile.getAbsolutePath(); return new Project(fileNameForFlashing(fullPathOfFile), fullPathOfFile, 0, null, false); } }
Example 6
Source File: DirectoryAdapter.java From nitroshare-android with MIT License | 5 votes |
private String getFileSummary(File file) { long size = file.length(); if (size < 1000) { return mContext.getResources().getQuantityString( R.plurals.activity_explorer_bytes, (int) size, size); } else if (size < 1000000) { return mContext.getString(R.string.activity_explorer_kb, size / 1000); } else if (size < 1000000000) { return mContext.getString(R.string.activity_explorer_mb, size / 1000000); } else { return mContext.getString(R.string.activity_explorer_gb, size / 1000000000); } }
Example 7
Source File: SmapUtil.java From packagedrone with Eclipse Public License 1.0 | 5 votes |
static byte[] readWhole(File input) throws IOException { FileInputStream inStream = new FileInputStream(input); int len = (int)input.length(); byte[] bytes = new byte[len]; if (inStream.read(bytes, 0, len) != len) { throw new IOException("expected size: " + len); } inStream.close(); return bytes; }
Example 8
Source File: FileMatch.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
/** * A file is accepted when all the criteria that have been set * are matched. * @param f The file to match against the configured criteria. * @return {@code true} if the file matches all criteria, * {@code false} otherwise. */ public boolean accept(File f) { // Directories are accepted if they match against the directory pattern. // if (f.isDirectory()) { if (directoryPattern != null && !f.getName().matches(directoryPattern)) return false; else return true; } // If we reach here, the f is not a directory. // // Files are accepted if they match all other conditions. // Check whether f matches filePattern if (filePattern != null && !f.getName().matches(filePattern)) return false; // Check whether f exceeeds size limit if (sizeExceedsMaxBytes > 0 && f.length() <= sizeExceedsMaxBytes) return false; // Check whether f was last modified after lastModifiedAfter if (lastModifiedAfter != null && lastModifiedAfter.after(new Date(f.lastModified()))) return false; // Check whether f was last modified before lastModifiedBefore if (lastModifiedBefore != null && lastModifiedBefore.before(new Date(f.lastModified()))) return false; // All conditions were met: accept file. return true; }
Example 9
Source File: CustomFilePart.java From Ouroboros with GNU General Public License v3.0 | 5 votes |
public CustomFilePart(String name, final File file) { super(name, (int)file.length(), new ArrayList<NameValuePair>() { { add(new BasicNameValuePair("filename", file.getName())); } }); List<String> validExt = Arrays.asList(".png", ".jpg", ".jpeg", ".gif"); String filePath = file.getAbsolutePath(); String extension = filePath.substring(filePath.lastIndexOf(".")); String contentType = (validExt.contains(extension)) ? "image/*" : "video/*"; getRawHeaders().set("Content-Type", contentType); this.file = file; }
Example 10
Source File: FileUtils.java From karate with MIT License | 5 votes |
public static void renameFileIfZeroBytes(String fileName) { File file = new File(fileName); if (!file.exists()) { LOGGER.warn("file not found, previous write operation may have failed: {}", fileName); } else if (file.length() == 0) { LOGGER.warn("file size is zero bytes, previous write operation may have failed: {}", fileName); try { File dest = new File(fileName + ".fail"); file.renameTo(dest); LOGGER.warn("renamed zero length file to: {}", dest.getName()); } catch (Exception e) { LOGGER.warn("failed to rename zero length file: {}", e.getMessage()); } } }
Example 11
Source File: LogbackLogManager.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@Override @Nullable @Guarded(by = STARTED) public InputStream getLogFileStream(final String fileName, final long from, final long count) throws IOException { log.debug("Retrieving log file: {}", fileName); // checking for platform or normalized path-separator (on unix these are the same) if (fileName.contains(File.pathSeparator) || fileName.contains("/")) { log.warn("Cannot retrieve log files with path separators in their name"); return null; } File file = getLogFile(fileName); if (file == null || !file.exists()) { log.warn("Log file does not exist: {}", fileName); return null; } long fromByte = from; long bytesCount = count; if (count < 0) { bytesCount = Math.abs(count); fromByte = Math.max(0, file.length() - bytesCount); } InputStream input = new BufferedInputStream(new FileInputStream(file)); if (fromByte == 0 && bytesCount >= file.length()) { return input; } else { input.skip(fromByte); return ByteStreams.limit(input, bytesCount); } }
Example 12
Source File: PackedSortedList.java From personaldnsfilter with GNU General Public License v2.0 | 5 votes |
public static PackedSortedList load(String path, boolean inMemory, ObjectPackagingManager objMgr) throws IOException { File f = new File(path); int size = (int) f.length(); if (!f.exists() || !f.canRead()) throw new IOException("Cannot read "+path); return new PackedSortedList(null, size / objMgr.objectSize(), inMemory, f, objMgr); }
Example 13
Source File: VersionedFile.java From Mycat2 with GNU General Public License v3.0 | 5 votes |
public long getSize() { long res = -1; File f = new File ( getCurrentVersionFileName() ); res = f.length(); return res; }
Example 14
Source File: ScanAndClearUnusedResource.java From ScanUnusedResouce with Apache License 2.0 | 5 votes |
private static void delUnusedJava(File dir) { if (codeMap == null || codeMap.size() == 0) { System.err.println("textMap没有初始化"); } if (dir == null || !dir.exists() || !dir.isDirectory()) { return; } for (File f : dir.listFiles()) { if (f.isDirectory()) { delUnusedJava(f); } else { String fileName = f.getAbsolutePath(); if (fileName.endsWith(".java") && !isExclude(f)) { if (!containsStringByJava(f)) { logD(f); codeMap.remove(f.getAbsolutePath()); delXMLBytes += f.length(); delFiles++; if (REAL_DEL) { f.delete(); } } } } } }
Example 15
Source File: HttpClient.java From ats-framework with Apache License 2.0 | 4 votes |
public void sendHttpRequest( String actionStep, String fileToSend, boolean hasParams ) throws Exception { log.info(actionStep + " -> Sending HTTP request to '" + urlConnection.getURL() + "'"); if (urlConnection.getDoOutput()) { stopWatch.step1_OpenConnectionForRequest(); OutputStream outputStream = urlConnection.getOutputStream(); // connect here stopWatch.step2_OpenedConnectionForRequest(); if (fileToSend != null) { File resourceFile = new File(fileToSend); InputStream is = new FileInputStream(resourceFile); try { if (hasParams) { if (resourceFile.length() > MAX_PARAMETERIZED_RESOURCE_FILE_SIZE) { throw new HttpClientException("The resource file '" + fileToSend + "' marked for parameterization is too large (max_size=" + MAX_PARAMETERIZED_RESOURCE_FILE_SIZE + ")"); } String fileContent = IoUtils.streamToString(is); fileContent = XmlUtilities.applyUserParameters(fileContent); if (log.isTraceEnabled()) { log.trace("Request contents after parameters applied:\n" + fileContent); } stopWatch.step3_StartSendingRequest(); try { outputStream.write(fileContent.getBytes()); outputStream.flush(); } finally { stopWatch.step4_EndSendingRequest(); } } else { if (log.isTraceEnabled()) { log.trace("Request data has no parameters marked so it is the same as the one in template files"); } byte[] buffer = new byte[CHUNK_LENGTH]; int numRead = 0; stopWatch.step3_StartSendingRequest(); try { while ( (numRead = is.read(buffer, 0, buffer.length)) != -1) { outputStream.write(buffer, 0, numRead); outputStream.flush(); } } finally { stopWatch.step4_EndSendingRequest(); } } } finally { IoUtils.closeStream(is); IoUtils.closeStream(outputStream); if (logTimer.isDebugEnabled()) { logTimer.debug(" Timer: Send file request time: " + stopWatch.getNetworkingTime()); } } } else { stopWatch.step3_StartSendingRequest(); try { outputStream.write(new byte[0]); outputStream.flush(); } finally { IoUtils.closeStream(outputStream); stopWatch.step4_EndSendingRequest(); } } } else { // Request with no body like GET, HEAD, DELETE stopWatch.setStateFromBeforeStep1ToAfterStep4(); // skip steps 1-4 } }
Example 16
Source File: FileUtil.java From entrada with GNU General Public License v3.0 | 4 votes |
public static long size(String file) { File f = new File(file); return f.exists() ? f.length() : -1; }
Example 17
Source File: SrcReader.java From APICloud-Studio with GNU General Public License v3.0 | 4 votes |
public SrcReader(File src_file) throws IOException { super(); this.file = src_file; Reader txt_reader = new FileReader(src_file); try { txt = new char[(int) src_file.length()]; txt_reader.read(txt); } finally { txt_reader.close(); } lines = new IntArray(txt.length / 20 + 20); boolean eol = true, cr = false; for (int i = 0; i < txt.length; i++) { if (eol) { lines.add(i); eol = false; } switch (txt[i]) { case '\u000B': case '\u000C': case '\u0085': case '\u2028': case '\u2029': { eol = true; cr = false; break; } case '\r': { if (cr) eol = true; cr = true; break; } case '\n': { if (cr) cr = false; eol = true; break; } default: { if (cr) eol = true; cr = false; } } } }
Example 18
Source File: FileUtil.java From talk-android with MIT License | 4 votes |
public static boolean isFileExist(String filePath, int fileSize) { File file = new File(filePath); return file.exists() && file.length() == fileSize; }
Example 19
Source File: DiskOfflineCompactionJUnitTest.java From gemfirexd-oss with Apache License 2.0 | 4 votes |
public void testbug41862() throws Exception { DiskStoreFactory dsf = cache.createDiskStoreFactory(); dsf.setAutoCompact(false); String name = "testbug41862"; DiskStore diskStore = dsf.create(name); File crfFile = new File(diskStore.getDiskDirs()[0], "BACKUP" + name + "_1.crf"); File drfFile = new File(diskStore.getDiskDirs()[0], "BACKUP" + name + "_1.drf"); File krfFile = new File(diskStore.getDiskDirs()[0], "BACKUP" + name + "_1.krf"); File ifFile = new File(diskStore.getDiskDirs()[0], "BACKUP" + name + ".if"); AttributesFactory af = new AttributesFactory(); af.setDiskStoreName(name); af.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); Region r = cache.createRegion("r", af.create()); int extra_byte_num_per_entry = InternalDataSerializer.calculateBytesForTSandDSID(getDSID((LocalRegion)r)); r.create("key1", "value1"); r.create("key2", "value2"); // to keep this oplog from going empty ((LocalRegion)r).getDiskStore().forceRoll(); r.create("key3", "value3"); r.remove("key1"); cache.close(); ds.disconnect(); DiskStoreImpl.validate(name, diskStore.getDiskDirs()); int crfsize = Oplog.OPLOG_DISK_STORE_REC_SIZE + Oplog.OPLOG_GEMFIRE_VERSION_REC_SIZE + getRVVSize(0, null, false) + Oplog.OPLOG_NEW_ENTRY_BASE_REC_SIZE; int createsize1 = getSize4Create(extra_byte_num_per_entry, "key1", "value1"); int createsize2 = getSize4Create(extra_byte_num_per_entry, "key2", "value2"); int createsize3 = getSize4Create(extra_byte_num_per_entry, "key3", "value3"); // 1 tombstone with key int tombstonesize1 = getSize4TombstoneWithKey(extra_byte_num_per_entry, "key1"); assertEquals(crfsize + createsize1 + createsize2, crfFile.length()); assertEquals(Oplog.OPLOG_DISK_STORE_REC_SIZE+Oplog.OPLOG_GEMFIRE_VERSION_REC_SIZE+getRVVSize(0, null, true), drfFile.length()); File crf2File = new File(diskStore.getDiskDirs()[0], "BACKUP" + name + "_2.crf"); File drf2File = new File(diskStore.getDiskDirs()[0], "BACKUP" + name + "_2.drf"); crfsize += (getRVVSize(1, new int[] {1}, false) - getRVVSize(0, null, false)); // adjust rvv size assertEquals(crfsize + createsize3 + tombstonesize1, crf2File.length()); assertEquals(Oplog.OPLOG_DISK_STORE_REC_SIZE+Oplog.OPLOG_GEMFIRE_VERSION_REC_SIZE+getRVVSize(1, new int[] {0}, true), drf2File.length()); long originalIfLength = ifFile.length(); DiskStoreImpl dsi = DiskStoreImpl.offlineCompact(name, diskStore.getDiskDirs(), false, -1); assertEquals(1, dsi.getDeadRecordCount()); assertEquals(3, dsi.getLiveEntryCount()); assertEquals(false, crfFile.exists()); assertEquals(false, drfFile.exists()); assertEquals(false, krfFile.exists()); // offline compaction did not change _2.crf and _2.drf not changed. assertEquals(crfsize + createsize3 + tombstonesize1, crf2File.length()); assertEquals(Oplog.OPLOG_DISK_STORE_REC_SIZE+Oplog.OPLOG_GEMFIRE_VERSION_REC_SIZE+getRVVSize(1, new int[] {0}, true), drf2File.length()); // offline compaction reset rvv to be empty, create-entry becomes one update-with-key-entry in _3.crf, // since there's no creates, then there's no OPLOG_NEW_ENTRY_BASE_REC_SIZE crfsize = Oplog.OPLOG_DISK_STORE_REC_SIZE + Oplog.OPLOG_GEMFIRE_VERSION_REC_SIZE + getRVVSize(1, new int[] {1}, false); int updatesize1 = getSize4UpdateWithKey(extra_byte_num_per_entry, "key3", "value3"); File crf3File = new File(diskStore.getDiskDirs()[0], "BACKUP" + name + "_3.crf"); File drf3File = new File(diskStore.getDiskDirs()[0], "BACKUP" + name + "_3.drf"); File krf3File = new File(diskStore.getDiskDirs()[0], "BACKUP" + name + "_3.krf"); assertEquals(true, krf3File.exists()); assertEquals(true, crf3File.exists()); assertEquals(true, drf3File.exists()); assertEquals(crfsize + updatesize1, crf3File.length()); assertEquals(Oplog.OPLOG_DISK_STORE_REC_SIZE+Oplog.OPLOG_GEMFIRE_VERSION_REC_SIZE+getRVVSize(1, new int[] {0}, true), drf3File.length()); assertEquals(originalIfLength, ifFile.length()); connectDSandCache(); dsf = cache.createDiskStoreFactory(); diskStore = dsf.create(name); af = new AttributesFactory(); af.setDiskStoreName(name); af.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE); r = cache.createRegion("r", af.create()); assertEquals(2, r.size()); assertEquals("value2", r.get("key2")); assertEquals("value3", r.get("key3")); // if test passed clean up files r.destroyRegion(); diskStore.destroy(); }
Example 20
Source File: CompiledScriptHolder.java From L2jBrasil with GNU General Public License v3.0 | 4 votes |
public CompiledScriptHolder(CompiledScript compiledScript, File scriptFile) { this(compiledScript, scriptFile.lastModified(), scriptFile.length()); }