java.io.File.length()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(11.2k)|赞(0)|评价(0)|浏览(807)

本文整理了Java中java.io.File.length()方法的一些代码示例,展示了File.length()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。File.length()方法的具体详情如下:
包路径:java.io.File
类名称:File
方法名:length

File.length介绍

[英]Returns the length of this file in bytes. Returns 0 if the file does not exist. The result for a directory is not defined.
[中]返回此文件的长度(字节)。如果文件不存在,则返回0。未定义目录的结果。

代码示例

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;
}

相关文章