Tabnine Logo
File.length
Code IndexAdd Tabnine to your IDE (free)

How to use
length
method
in
java.io.File

Best Java code snippets using java.io.File.length (Showing top 20 results out of 39,690)

Refine searchRefine arrow

  • File.<init>
  • FileInputStream.<init>
  • File.exists
  • BufferedInputStream.<init>
  • File.getName
  • PrintStream.println
  • FileInputStream.close
  • FileInputStream.read
  • File.getAbsolutePath
canonical example by Tabnine

public long getDirectorySize(File file) {
 if (!file.exists()) {
  return 0;
 }
 if (file.isFile()) {
  return file.length();
 }
 File[] files;
 if (!file.isDirectory() || (files = file.listFiles()) == null) {
  return 0;
 }
 return Arrays.stream(files).mapToLong(f -> getDirectorySize(f)).sum();
}
origin: Tencent/tinker

public static boolean isLegalFile(String path) {
  if (path == null) {
    return false;
  }
  File file = new File(path);
  return file.exists() && file.isFile() && file.length() > 0;
}
origin: Tencent/tinker

public static void bsdiff(File oldFile, File newFile, File diffFile) throws IOException {
  InputStream oldInputStream = new BufferedInputStream(new FileInputStream(oldFile));
  InputStream newInputStream = new BufferedInputStream(new FileInputStream(newFile));
  OutputStream diffOutputStream = new FileOutputStream(diffFile);
  try {
    byte[] diffBytes = bsdiff(oldInputStream, (int) oldFile.length(), newInputStream, (int) newFile.length());
    diffOutputStream.write(diffBytes);
  } finally {
    diffOutputStream.close();
  }
}
origin: stackoverflow.com

 File file = new File("a.txt");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();

String str = new String(data, "UTF-8");
origin: stackoverflow.com

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 if(ISSUE_DOWNLOAD_STATUS.intValue()==ECMConstant.ECM_DOWNLOADING){
   File file=new File(DESTINATION_PATH);
   if(file.exists()){
      downloaded = (int) file.length();
      connection.setRequestProperty("Range", "bytes="+(file.length())+"-");
   }
 }else{
   connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
 }
 connection.setDoInput(true);
 connection.setDoOutput(true);
 progressBar.setMax(connection.getContentLength());
  in = new BufferedInputStream(connection.getInputStream());
  fos=(downloaded==0)? new FileOutputStream(DESTINATION_PATH): new FileOutputStream(DESTINATION_PATH,true);
  bout = new BufferedOutputStream(fos, 1024);
 byte[] data = new byte[1024];
 int x = 0;
 while ((x = in.read(data, 0, 1024)) >= 0) {
   bout.write(data, 0, x);
    downloaded += x;
    progressBar.setProgress(downloaded);
 }
origin: commons-io/commons-io

@Test public void testResourceToString_ExistingResourceAtRootPackage_WithClassLoader() throws Exception {
  final long fileSize = new File(getClass().getResource("/test-file-simple-utf8.bin").getFile()).length();
  final String content = IOUtils.resourceToString(
      "test-file-simple-utf8.bin",
      StandardCharsets.UTF_8,
      ClassLoader.getSystemClassLoader()
  );
  assertNotNull(content);
  assertEquals(fileSize, content.getBytes().length);
}
origin: Tencent/tinker

private void addTestDex() throws IOException {
  //write test dex
  String dexMode = "jar";
  if (config.mDexRaw) {
    dexMode = "raw";
  }
  final InputStream is = DexDiffDecoder.class.getResourceAsStream("/" + TEST_DEX_NAME);
  String md5 = MD5.getMD5(is, 1024);
  is.close();
  String meta = TEST_DEX_NAME + "," + "" + "," + md5 + "," + md5 + "," + 0 + "," + 0 + "," + 0 + "," + dexMode;
  File dest = new File(config.mTempResultDir + "/" + TEST_DEX_NAME);
  FileOperation.copyResourceUsingStream(TEST_DEX_NAME, dest);
  Logger.d("\nAdd test install result dex: %s, size:%d", dest.getAbsolutePath(), dest.length());
  Logger.d("DexDecoder:write test dex meta file data: %s", meta);
  metaWriter.writeLineToInfoFile(meta);
}
origin: apache/incubator-pinot

/**
 * Compares and prints the index size for the raw and dictionary encoded columns.
 *
 * @param segment Segment to compare
 */
private void compareIndexSizes(IndexSegment segment, File segmentDir, String fwdIndexColumn, String rawIndexColumn) {
 String filePrefix = segmentDir.getAbsolutePath() + File.separator;
 File rawIndexFile = new File(filePrefix + rawIndexColumn + V1Constants.Indexes.RAW_SV_FORWARD_INDEX_FILE_EXTENSION);
 String extension = (segment.getDataSource(_fwdIndexColumn).getDataSourceMetadata().isSorted())
   ? V1Constants.Indexes.SORTED_SV_FORWARD_INDEX_FILE_EXTENSION
   : V1Constants.Indexes.UNSORTED_SV_FORWARD_INDEX_FILE_EXTENSION;
 File fwdIndexFile = new File(filePrefix + _fwdIndexColumn + extension);
 File fwdIndexDictFile = new File(filePrefix + _fwdIndexColumn + V1Constants.Dict.FILE_EXTENSION);
 long rawIndexSize = rawIndexFile.length();
 long fwdIndexSize = fwdIndexFile.length() + fwdIndexDictFile.length();
 System.out.println("Raw index size: " + toMegaBytes(rawIndexSize) + " MB.");
 System.out.println("Fwd index size: " + toMegaBytes(fwdIndexSize) + " MB.");
 System.out.println("Storage space saving: " + ((fwdIndexSize - rawIndexSize) * 100.0 / fwdIndexSize) + " %");
}
origin: AsyncHttpClient/async-http-client

private static MultipartBody buildMultipart() {
 List<Part> parts = new ArrayList<>(PARTS);
 try {
  File testFile = getTestfile();
  InputStream inputStream = new BufferedInputStream(new FileInputStream(testFile));
  parts.add(new InputStreamPart("isPart", inputStream, testFile.getName(), testFile.length()));
 } catch (URISyntaxException | FileNotFoundException e) {
  throw new ExceptionInInitializerError(e);
 }
 return MultipartUtils.newMultipartBody(parts, EmptyHttpHeaders.INSTANCE);
}
origin: stackoverflow.com

 private DropboxAPI<AndroidAuthSession> mDBApi;//global variable

File tmpFile = new File(fullPath, "IMG_2012-03-12_10-22-09_thumb.jpg");

FileInputStream fis = new FileInputStream(tmpFile);

      try {
        DropboxAPI.Entry newEntry = mDBApi.putFileOverwrite("IMG_2012-03-12_10-22-09_thumb.jpg", fis, tmpFile.length(), null);
      } catch (DropboxUnlinkedException e) {
        Log.e("DbExampleLog", "User has unlinked.");
      } catch (DropboxException e) {
        Log.e("DbExampleLog", "Something went wrong while uploading.");
      }
origin: redisson/redisson

  return;
mutationCount++;
System.out.println("resizing underlying "+mappedFile+" to "+required+" numElem:"+numElem);
long tim = System.currentTimeMillis();
((MMFBytez) memory).freeAndClose();
memory = null;
try {
  File mf = new File(mappedFile);
  FileOutputStream f = new FileOutputStream(mf,true);
  long len = mf.length();
  required = required + Math.min(required,maxgrowbytes);
  byte[] toWrite = new byte[1000];
  resetMem(mappedFile, mf.length());
  System.out.println("resizing done in "+(System.currentTimeMillis()-tim)+" numElemAfter:"+numElem);
} catch (FileNotFoundException e) {
  e.printStackTrace();
origin: apache/kylin

protected void setDownloadResponse(String downloadFile, final HttpServletResponse response) {
  File file = new File(downloadFile);
  try (InputStream fileInputStream = new FileInputStream(file);
      OutputStream output = response.getOutputStream()) {
    response.reset();
    response.setContentType("application/octet-stream");
    response.setContentLength((int) (file.length()));
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
    IOUtils.copyLarge(fileInputStream, output);
    output.flush();
  } catch (IOException e) {
    throw new InternalErrorException("Failed to download file: " + e.getMessage(), e);
  }
}
origin: commons-io/commons-io

@Test
public void testFileUtils() throws Exception {
  // Loads file from classpath
  final File file1 = new File(getTestDirectory(), "test.txt");
  final String filename = file1.getAbsolutePath();
  //Create test file on-the-fly (used to be in CVS)
  try (OutputStream out = new FileOutputStream(file1)) {
    out.write("This is a test".getBytes("UTF-8"));
  }
  final File file2 = new File(getTestDirectory(), "test2.txt");
  FileUtils.writeStringToFile(file2, filename, "UTF-8");
  assertTrue(file2.exists());
  assertTrue(file2.length() > 0);
  final String file2contents = FileUtils.readFileToString(file2, "UTF-8");
  assertTrue(
      "Second file's contents correct",
      filename.equals(file2contents));
  assertTrue(file2.delete());
  final String contents = FileUtils.readFileToString(new File(filename), "UTF-8");
  assertEquals("FileUtils.fileRead()", "This is a test", contents);
}
origin: lets-blade/blade

@Override
public void download(@NonNull String fileName, @NonNull File file) throws Exception {
  if (!file.exists() || !file.isFile()) {
    throw new NotFoundException("Not found file: " + file.getPath());
  }
  String contentType = StringKit.mimeType(file.getName());
  headers.put("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859_1"));
  headers.put(HttpConst.CONTENT_LENGTH.toString(), String.valueOf(file.length()));
  headers.put(HttpConst.CONTENT_TYPE_STRING, contentType);
  this.body = new StreamBody(new FileInputStream(file));
}
origin: Tencent/tinker

/**
 * if bsDiff result is too larger, just treat it as newly file
 * @param bsDiffFile
 * @param newFile
 * @return
 */
public static boolean checkBsDiffFileSize(File bsDiffFile, File newFile) {
  if (!bsDiffFile.exists()) {
    throw new TinkerPatchException("can not find the bsDiff file:" + bsDiffFile.getAbsolutePath());
  }
  //check bsDiffFile file size
  double ratio = bsDiffFile.length() / (double) newFile.length();
  if (ratio > TypedValue.BSDIFF_PATCH_MAX_RATIO) {
    Logger.e("bsDiff patch file:%s, size:%dk, new file:%s, size:%dk. patch file is too large, treat it as newly file to save patch time!",
      bsDiffFile.getName(),
      bsDiffFile.length() / 1024,
      newFile.getName(),
      newFile.length() / 1024
    );
    return false;
  }
  return true;
}
origin: web3j/web3j

public static byte[] readBytes(File file) throws IOException {
  byte[] bytes = new byte[(int) file.length()];
  try (FileInputStream fileInputStream = new FileInputStream(file)) {
    fileInputStream.read(bytes);
  }
  return bytes;
}
origin: libgdx/libgdx

/** Returns the length in bytes of this file, or 0 if this file is a directory, does not exist, or the size cannot otherwise be
 * determined. */
public long length () {
  if (type == FileType.Classpath || (type == FileType.Internal && !file.exists())) {
    InputStream input = read();
    try {
      return input.available();
    } catch (Exception ignored) {
    } finally {
      StreamUtils.closeQuietly(input);
    }
    return 0;
  }
  return file().length();
}
origin: oblac/jodd

/**
 * Prepares response for file download with provided mime type.
 */
public static void prepareDownload(final HttpServletResponse response, final File file, final String mimeType) {
  if (!file.exists()) {
    throw new IllegalArgumentException("File not found: " + file);
  }
  if (file.length() > Integer.MAX_VALUE) {
    throw new IllegalArgumentException("File too big: " + file);
  }
  prepareResponse(response, file.getAbsolutePath(), mimeType, (int) file.length());
}
origin: hankcs/HanLP

public void open(String fileName) throws IOException
{
  File file = new File(fileName);
  size = (int) file.length() / UNIT_SIZE;
  check = new int[size];
  base = new int[size];
  DataInputStream is = null;
  try
  {
    is = new DataInputStream(new BufferedInputStream(
        IOUtil.newInputStream(fileName), BUF_SIZE));
    for (int i = 0; i < size; i++)
    {
      base[i] = is.readInt();
      check[i] = is.readInt();
    }
  }
  finally
  {
    if (is != null)
      is.close();
  }
}
origin: osmandapp/Osmand

/**
 * Determine whether a file is a ZIP File.
 */
public static boolean isZipFile(File file) throws IOException {
  if (file.isDirectory()) {
    return false;
  }
  if (!file.canRead()) {
    throw new IOException("Cannot read file " + file.getAbsolutePath());
  }
  if (file.length() < 4) {
    return false;
  }
  FileInputStream in = new FileInputStream(file);
  int test = readInt(in);
  in.close();
  return test == 0x504b0304;
}
java.ioFilelength

Javadoc

Returns the length of this file in bytes. Returns 0 if the file does not exist. The result for a directory is not defined.

Popular methods of File

  • <init>
    Creates a new File instance by converting the givenfile: URI into an abstract pathname. The exact fo
  • exists
    Tests whether the file or directory denoted by this abstract pathname exists.
  • getAbsolutePath
    Returns the absolute pathname string of this abstract pathname. If this abstract pathname is already
  • getName
    Returns the name of the file or directory denoted by this abstract pathname. This is just the last n
  • isDirectory
  • mkdirs
  • delete
    Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a director
  • listFiles
    Returns an array of abstract pathnames denoting the files and directories in the directory denoted b
  • getParentFile
    Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not
  • getPath
    Converts this abstract pathname into a pathname string. The resulting string uses the #separator to
  • isFile
  • toURI
  • isFile,
  • toURI,
  • createTempFile,
  • createNewFile,
  • toPath,
  • mkdir,
  • lastModified,
  • toString,
  • getCanonicalPath

Popular in Java

  • Start an intent from android
  • scheduleAtFixedRate (Timer)
  • runOnUiThread (Activity)
  • getSharedPreferences (Context)
  • ResultSet (java.sql)
    An interface for an object which represents a database table entry, returned as the result of the qu
  • BoxLayout (javax.swing)
  • JButton (javax.swing)
  • JCheckBox (javax.swing)
  • XPath (javax.xml.xpath)
    XPath provides access to the XPath evaluation environment and expressions. Evaluation of XPath Expr
  • SAXParseException (org.xml.sax)
    Encapsulate an XML parse error or warning.> This module, both source code and documentation, is in t
  • From CI to AI: The AI layer in your organization
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now