java.io.File类的使用及代码示例

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

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

File介绍

[英]An "abstract" representation of a file system entity identified by a pathname. The pathname may be absolute (relative to the root directory of the file system) or relative to the current directory in which the program is running.

The actual file referenced by a File may or may not exist. It may also, despite the name File, be a directory or other non-regular file.

This class provides limited functionality for getting/setting file permissions, file type, and last modified time.

On Android strings are converted to UTF-8 byte sequences when sending filenames to the operating system, and byte sequences returned by the operating system (from the various list methods) are converted to strings by decoding them as UTF-8 byte sequences.
[中]由路径名标识的文件系统实体的“抽象”表示形式。路径名可以是绝对的(相对于文件系统的根目录),也可以是相对于运行程序的当前目录。
文件引用的实际文件可能存在,也可能不存在。它也可以是一个目录或其他非常规文件,而不考虑文件名。
此类为获取/设置文件权限、文件类型和上次修改时间提供了有限的功能。
在Android上,当向操作系统发送文件名时,字符串被转换为UTF-8字节序列,操作系统返回的字节序列(来自各种列表方法)通过解码为UTF-8字节序列被转换为字符串。

代码示例

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

canonical example by Tabnine

public void zipFile(File srcFile, File zipFile) throws IOException {
 try (FileInputStream fis = new FileInputStream(srcFile);
   ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
  zos.putNextEntry(new ZipEntry(srcFile.getName()));
  int len;
  byte[] buffer = new byte[1024];
  while ((len = fis.read(buffer)) > 0) {
   zos.write(buffer, 0, len);
  }
  zos.closeEntry();
 }
}

代码示例来源:origin: iBotPeaches/Apktool

public static void cpdir(File src, File dest) throws BrutException {
  dest.mkdirs();
  File[] files = src.listFiles();
  for (int i = 0; i < files.length; i++) {
    File file = files[i];
    File destFile = new File(dest.getPath() + File.separatorChar
      + file.getName());
    if (file.isDirectory()) {
      cpdir(file, destFile);
      continue;
    }
    try {
      InputStream in = new FileInputStream(file);
      OutputStream out = new FileOutputStream(destFile);
      IOUtils.copy(in, out);
      in.close();
      out.close();
    } catch (IOException ex) {
      throw new BrutException("Could not copy file: " + file, ex);
    }
  }
}

代码示例来源:origin: libgdx/libgdx

private void copyAndReplace (String outputDir, Project project, Map<String, String> values) {
  File out = new File(outputDir);
  if (!out.exists() && !out.mkdirs()) {
    throw new RuntimeException("Couldn't create output directory '" + out.getAbsolutePath() + "'");
  }
  for (ProjectFile file : project.files) {
    copyFile(file, out, values);
  }
}

代码示例来源:origin: stackoverflow.com

void deleteRecursive(File fileOrDirectory) {
  if (fileOrDirectory.isDirectory())
    for (File child : fileOrDirectory.listFiles())
      deleteRecursive(child);

  fileOrDirectory.delete();
}

代码示例来源:origin: stackoverflow.com

public class DownloadTask extends GroundyTask {    
  public static final String PARAM_URL = "com.groundy.sample.param.url";

  @Override
  protected boolean doInBackground() {
    try {
      String url = getParameters().getString(PARAM_URL);
      File dest = new File(getContext().getFilesDir(), new File(url).getName());
      DownloadUtils.downloadFile(getContext(), url, dest, DownloadUtils.getDownloadListenerForTask(this));
      return true;
    } catch (Exception pokemon) {
      return false;
    }
  }
}

代码示例来源:origin: iluwatar/java-design-patterns

/**
 * @return True, if the file given exists, false otherwise.
 */
public boolean fileExists() {
 return new File(this.fileName).exists();
}

代码示例来源:origin: stackoverflow.com

File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) { 
  // do something
}

代码示例来源:origin: apache/incubator-druid

@Test
public void testDecompressBzip2() throws IOException
{
 final File tmpDir = temporaryFolder.newFolder("testDecompressBzip2");
 final File bzFile = new File(tmpDir, testFile.getName() + ".bz2");
 Assert.assertFalse(bzFile.exists());
 try (final OutputStream out = new BZip2CompressorOutputStream(new FileOutputStream(bzFile))) {
  ByteStreams.copy(new FileInputStream(testFile), out);
 }
 try (final InputStream inputStream = CompressionUtils.decompress(new FileInputStream(bzFile), bzFile.getName())) {
  assertGoodDataStream(inputStream);
 }
}

代码示例来源:origin: google/guava

/**
 * Returns the URLs in the class path specified by the {@code java.class.path} {@linkplain
 * System#getProperty system property}.
 */
@VisibleForTesting // TODO(b/65488446): Make this a public API.
static ImmutableList<URL> parseJavaClassPath() {
 ImmutableList.Builder<URL> urls = ImmutableList.builder();
 for (String entry : Splitter.on(PATH_SEPARATOR.value()).split(JAVA_CLASS_PATH.value())) {
  try {
   try {
    urls.add(new File(entry).toURI().toURL());
   } catch (SecurityException e) { // File.toURI checks to see if the file is a directory
    urls.add(new URL("file", null, new File(entry).getAbsolutePath()));
   }
  } catch (MalformedURLException e) {
   logger.log(WARNING, "malformed classpath entry: " + entry, e);
  }
 }
 return urls.build();
}

代码示例来源:origin: prestodb/presto

private void writeZone(File outputDir, DateTimeZoneBuilder builder, DateTimeZone tz) throws IOException {
  if (ZoneInfoLogger.verbose()) {
    System.out.println("Writing " + tz.getID());
  }
  File file = new File(outputDir, tz.getID());
  if (!file.getParentFile().exists()) {
    file.getParentFile().mkdirs();
  }
  OutputStream out = new FileOutputStream(file);
  try {
    builder.writeTo(tz.getID(), out);
  } finally {
    out.close();
  }
  // Test if it can be read back.
  InputStream in = new FileInputStream(file);
  DateTimeZone tz2 = DateTimeZoneBuilder.readFrom(in, tz.getID());
  in.close();
  if (!tz.equals(tz2)) {
    System.out.println("*e* Error in " + tz.getID() +
              ": Didn't read properly from file");
  }
}

代码示例来源:origin: commons-io/commons-io

@Test
public void testCanRead() throws Exception {
  final File readOnlyFile = new File(getTestDirectory(), "read-only-file1.txt");
  if (!readOnlyFile.getParentFile().exists()) {
    throw new IOException("Cannot create file " + readOnlyFile
        + " as the parent directory does not exist");
  }
  try (final BufferedOutputStream output =
      new BufferedOutputStream(new FileOutputStream(readOnlyFile))){
    TestUtils.generateTestData(output, 32);
  }
  readOnlyFile.setReadOnly();
  assertFiltering(CanReadFileFilter.CAN_READ,  readOnlyFile, true);
  assertFiltering(CanReadFileFilter.CANNOT_READ,  readOnlyFile, false);
  assertFiltering(CanReadFileFilter.READ_ONLY, readOnlyFile, true);
  readOnlyFile.delete();
}

代码示例来源:origin: libgdx/libgdx

private File extractFile (String sourcePath, String sourceCrc, File extractedFile) throws IOException {
  String extractedCrc = null;
  if (extractedFile.exists()) {
    try {
      extractedCrc = crc(new FileInputStream(extractedFile));
    } catch (FileNotFoundException ignored) {
    try {
      input = readFile(sourcePath);
      extractedFile.getParentFile().mkdirs();
      output = new FileOutputStream(extractedFile);
      byte[] buffer = new byte[4096];
      while (true) {
        int length = input.read(buffer);
        if (length == -1) break;
        output.write(buffer, 0, length);
      throw new GdxRuntimeException("Error extracting file: " + sourcePath + "\nTo: " + extractedFile.getAbsolutePath(),
        ex);
    } finally {

代码示例来源:origin: Blankj/AndroidUtilCode

final ZipEntry entry,
                 final String name) throws IOException {
File file = new File(destDir, name);
files.add(file);
if (entry.isDirectory()) {
  OutputStream out = null;
  try {
    in = new BufferedInputStream(zip.getInputStream(entry));
    out = new BufferedOutputStream(new FileOutputStream(file));
    byte buffer[] = new byte[BUFFER_LEN];
    int len;
    while ((len = in.read(buffer)) != -1) {
      out.write(buffer, 0, len);
      in.close();
      out.close();

代码示例来源:origin: google/guava

@AndroidIncompatible // Android forbids null parent ClassLoader
public void testClassPathEntries_URLClassLoader_noParent() throws Exception {
 URL url1 = new URL("file:/a");
 URL url2 = new URL("file:/b");
 URLClassLoader classloader = new URLClassLoader(new URL[] {url1, url2}, null);
 assertThat(ClassPath.Scanner.getClassPathEntries(classloader))
   .containsExactly(new File("/a"), classloader, new File("/b"), classloader);
}

代码示例来源:origin: apache/zookeeper

public void chop() {
  File targetFile = new File(txnLogFile.getParentFile(), txnLogFile.getName() + ".chopped" + zxid);
  try (
      InputStream is = new BufferedInputStream(new FileInputStream(txnLogFile));
      OutputStream os = new BufferedOutputStream(new FileOutputStream(targetFile))
  ) {
    if (!LogChopper.chop(is, os, zxid)) {
      throw new TxnLogToolkitException(ExitCode.INVALID_INVOCATION.getValue(), "Failed to chop %s", txnLogFile.getName());
    }
  } catch (Exception e) {
    System.out.println("Got exception: " + e.getMessage());
  }
}

代码示例来源:origin: stackoverflow.com

// Assume block needs to be inside a Try/Catch block.
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
Integer counter = 0;
File file = new File(path, "FitnessGirl"+counter+".jpg"); // the File to save , append increasing numeric counter to prevent files from getting overwritten.
fOut = new FileOutputStream(file);

Bitmap pictureBitmap = getImageBitmap(myurl); // obtaining the Bitmap
pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
fOut.flush(); // Not really required
fOut.close(); // do not forget to close the stream

MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());

代码示例来源:origin: stackoverflow.com

File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();

  for (int i = 0; i < listOfFiles.length; i++) {
   if (listOfFiles[i].isFile()) {
    System.out.println("File " + listOfFiles[i].getName());
   } else if (listOfFiles[i].isDirectory()) {
    System.out.println("Directory " + listOfFiles[i].getName());
   }
  }

代码示例来源:origin: redisson/redisson

/**
 * {@inheritDoc}
 */
public Manifest getManifest() throws IOException {
  File file = new File(folder, JarFile.MANIFEST_NAME);
  if (file.exists()) {
    InputStream inputStream = new FileInputStream(file);
    try {
      return new Manifest(inputStream);
    } finally {
      inputStream.close();
    }
  } else {
    return NO_MANIFEST;
  }
}

代码示例来源:origin: org.testng/testng

public static void copyFile(InputStream from, File to) throws IOException {
 if (! to.getParentFile().exists()) {
  to.getParentFile().mkdirs();
 }
 try (OutputStream os = new FileOutputStream(to)) {
  byte[] buffer = new byte[65536];
  int count = from.read(buffer);
  while (count > 0) {
   os.write(buffer, 0, count);
   count = from.read(buffer);
  }
 }
}

相关文章