List of usage examples for java.io File length
public long length()
From source file:Main.java
public static byte[] readBytes(File file) throws IOException { //check/* w ww .jav a 2 s. c om*/ if (!file.exists()) { throw new FileNotFoundException("File not exist: " + file); } if (!file.isFile()) { throw new IOException("Not a file:" + file); } long len = file.length(); if (len >= Integer.MAX_VALUE) { throw new IOException("File is larger then max array size"); } byte[] bytes = new byte[(int) len]; FileInputStream in = null; try { in = new FileInputStream(file); in.read(bytes); } finally { close(in); } return bytes; }
From source file:Main.java
/** * Save a media URI into the download directory * @param context the context/*w ww .j av a2s . c o m*/ * @param srcFile the source file. * @param filename the filename (optional) * @return the downloads file path */ @SuppressLint("NewApi") public static String saveMediaIntoDownloads(Context context, File srcFile, String filename, String mimeType) { String fullFilePath = saveFileInto(context, srcFile, Environment.DIRECTORY_DOWNLOADS, filename); if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { if (null != fullFilePath) { DownloadManager downloadManager = (DownloadManager) context .getSystemService(Context.DOWNLOAD_SERVICE); try { File file = new File(fullFilePath); downloadManager.addCompletedDownload(file.getName(), file.getName(), true, mimeType, file.getAbsolutePath(), file.length(), true); } catch (Exception e) { } } } return fullFilePath; }
From source file:com.doplgangr.secrecy.Util.java
public static Map<String, java.io.File> getAllStorageLocations() { Map<String, java.io.File> map = new TreeMap<String, File>(); List<String> mMounts = new ArrayList<String>(99); //List<String> mVold = new ArrayList<String>(99); mMounts.add(Environment.getExternalStorageDirectory().getAbsolutePath()); try {/*from w w w .j a va2 s.c o m*/ java.io.File mountFile = new java.io.File("/proc/mounts"); if (mountFile.exists()) { Scanner scanner = new Scanner(mountFile); while (scanner.hasNext()) { String line = scanner.nextLine(); //if (line.startsWith("/dev/block/vold/")) { String[] lineElements = line.split(" "); String element = lineElements[1]; mMounts.add(element); } } } catch (Exception e) { e.printStackTrace(); } /** try { java.io.File voldFile = new java.io.File("/system/etc/vold.fstab"); if (voldFile.exists()) { Scanner scanner = new Scanner(voldFile); while (scanner.hasNext()) { String line = scanner.nextLine(); //if (line.startsWith("dev_mount")) { String[] lineElements = line.split(" "); String element = lineElements[2]; if (element.contains(":")) element = element.substring(0, element.indexOf(":")); mVold.add(element); } } } catch (Exception e) { e.printStackTrace(); } **/ /* for (int i = 0; i < mMounts.size(); i++) { String mount = mMounts.get(i); if (!mVold.contains(mount)) mMounts.remove(i--); } mVold.clear(); */ List<String> mountHash = new ArrayList<String>(99); for (String mount : mMounts) { java.io.File root = new java.io.File(mount); Util.log(mount, "is checked"); Util.log(mount, root.exists(), root.isDirectory(), canWrite(root)); if (canWrite(root)) { Util.log(mount, "is writable"); java.io.File[] list = root.listFiles(); String hash = "["; if (list != null) for (java.io.File f : list) hash += f.getName().hashCode() + ":" + f.length() + ", "; hash += "]"; if (!mountHash.contains(hash)) { String key = root.getAbsolutePath() + " (" + org.apache.commons.io.FileUtils.byteCountToDisplaySize(root.getUsableSpace()) + " free space)"; mountHash.add(hash); map.put(key, root); } } } mMounts.clear(); return map; }
From source file:com.openideals.android.net.HttpManager.java
public static String uploadFile(String serviceEndpoint, Properties properties, String fileParam, String file) throws Exception { HttpClient httpClient = new DefaultHttpClient(); HttpPost request = new HttpPost(serviceEndpoint); MultipartEntity entity = new MultipartEntity(); Iterator<Map.Entry<Object, Object>> i = properties.entrySet().iterator(); while (i.hasNext()) { Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) i.next(); String key = (String) entry.getKey(); String val = (String) entry.getValue(); entity.addPart(key, new StringBody(val)); }// w w w . j a v a 2 s .c o m File upload = new File(file); Log.i("httpman", "upload file (" + upload.getAbsolutePath() + ") size=" + upload.length()); entity.addPart(fileParam, new FileBody(upload)); request.setEntity(entity); HttpResponse response = httpClient.execute(request); int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { } else { } return response.toString(); }
From source file:info.guardianproject.net.http.HttpManager.java
public static String uploadFile(String serviceEndpoint, Properties properties, String fileParam, String file) throws Exception { HttpClient httpClient = new DefaultHttpClient(); HttpPost request = new HttpPost(serviceEndpoint); MultipartEntity entity = new MultipartEntity(); Iterator<Map.Entry<Object, Object>> i = properties.entrySet().iterator(); while (i.hasNext()) { Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) i.next(); String key = (String) entry.getKey(); String val = (String) entry.getValue(); entity.addPart(key, new StringBody(val)); }//from w ww .jav a 2 s. c o m File upload = new File(file); Log.i("httpman", "upload file (" + upload.getAbsolutePath() + ") size=" + upload.length()); entity.addPart(fileParam, new FileBody(upload)); request.setEntity(entity); HttpResponse response = httpClient.execute(request); int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { } else { } return response.toString(); }
From source file:de.bps.onyx.util.SummaryCheckSumValidator.java
/** * Validates the Onyx test result summary pages checksum. * /*from w w w. j a v a2 s .c o m*/ * @param file * The file containing the summary HTML * @return SummaryChecksumValidatorResult structure. The contained validated * field contains the validation result. * * @see SummaryChecksumValidatorResult */ public static SummaryChecksumValidatorResult validate(final File file) { FileInputStream fis = null; final ByteArrayOutputStream baos = new ByteArrayOutputStream((int) file.length()); try { fis = new FileInputStream(file); final byte[] buf = new byte[102400]; int read = 0; while ((read = fis.read(buf)) >= 0) { baos.write(buf, 0, read); } } catch (final IOException e) { // log.error("Error reading file to validate: " + file.getAbsolutePath(), e); final SummaryChecksumValidatorResult result = new SummaryChecksumValidatorResult(); result.result = "onyx.summary.validation.result.error.reading.file"; result.info = file.getAbsolutePath() + " - " + e.getMessage(); return result; } finally { try { if (fis != null) { fis.close(); fis = null; } } catch (final Exception e) { // ignore } } try { baos.flush(); } catch (final IOException e) { // ignore } final String html = baos.toString(); try { baos.close(); } catch (final IOException e) { // ignore } return internalValidate(html); }
From source file:in.goahead.apps.util.URLUtils.java
public static String DownloadFileFromURL(String url, String savePath) throws MalformedURLException, IOException { String fileName = null;/*from www.j a v a 2 s . c om*/ fileName = getURLFileName(url); String absoluteFileName = savePath + "/" + fileName; Logger.debug(absoluteFileName); File f = new File(absoluteFileName); long skipBytes = 0; if (f.exists()) { skipBytes = f.length(); } Logger.debug(skipBytes); InputStream fileDownloadStream = OpenURL(url, skipBytes); DownloadStream(fileDownloadStream, absoluteFileName, skipBytes); return fileName; }
From source file:cz.autoclient.league_of_legends.DataLoader.java
public static String stringFromFile(File file) throws FileNotFoundException { char[] buff = new char[(int) file.length()]; try {/*from w w w . j a v a 2 s . c om*/ (new FileReader(file)).read(buff); } catch (IOException e) { throw new FileNotFoundException("Invalid file."); } return new StringBuilder().append(buff).toString(); }
From source file:Main.java
public static long getFolderSize(File folder) throws IllegalArgumentException { // Validate//from w ww .j a va 2s.c o m if (folder == null || !folder.isDirectory()) throw new IllegalArgumentException("Invalid folder "); String list[] = folder.list(); if (list == null || list.length < 1) return 0; // Get size File object = null; long folderSize = 0; for (int i = 0; i < list.length; i++) { object = new File(folder, list[i]); if (object.isDirectory()) folderSize += getFolderSize(object); else if (object.isFile()) folderSize += object.length(); } return folderSize; }
From source file:com.parse.ParseKeyValueCache.java
static void saveToKeyValueCache(String key, String value) { synchronized (MUTEX_IO) { File prior = getKeyValueCacheFile(key); if (prior != null) { prior.delete();/*from w ww . ja va2 s .c o m*/ } File f = createKeyValueCacheFile(key); try { ParseFileUtils.writeByteArrayToFile(f, value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // do nothing } catch (IOException e) { // do nothing } // Check if we should kick out old cache entries File[] files = getKeyValueCacheDir().listFiles(); // We still need this check since dir.mkdir() may fail if (files == null || files.length == 0) { return; } int numFiles = files.length; int numBytes = 0; for (File file : files) { numBytes += file.length(); } // If we do not need to clear the cache, simply return if (numFiles <= maxKeyValueCacheFiles && numBytes <= maxKeyValueCacheBytes) { return; } // We need to kick out some cache entries. // Sort oldest-first. We touch on read so mtime is really LRU. // Sometimes (i.e. tests) the time of lastModified isn't granular enough, // so we resort // to sorting by the file name which is always prepended with time in ms Arrays.sort(files, new Comparator<File>() { @Override public int compare(File f1, File f2) { int dateCompare = Long.valueOf(f1.lastModified()).compareTo(f2.lastModified()); if (dateCompare != 0) { return dateCompare; } else { return f1.getName().compareTo(f2.getName()); } } }); for (File file : files) { numFiles--; numBytes -= file.length(); file.delete(); if (numFiles <= maxKeyValueCacheFiles && numBytes <= maxKeyValueCacheBytes) { break; } } } }