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

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

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

File.getName介绍

[英]Returns the name of the file or directory represented by this file.
[中]返回此文件表示的文件或目录的名称。

代码示例

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: 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: 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: jenkinsci/jenkins

@Override
  public boolean accept(File pathname) {
    return pathname.isDirectory() && !existing.contains(pathname.getName());
  }
})) {

代码示例来源:origin: facebook/stetho

/**
 * Subclassing this function is intended to provide custom open behaviour on a per-file basis.
 */
protected @SQLiteOpenOptions int determineOpenOptions(File databaseFile) {
 @SQLiteOpenOptions int flags = 0;
 // Try to guess if we should be using write-ahead logging.  If this heuristic fails
 // developers are expected to subclass this provider and explicitly assert the connection.
 File walFile = new File(databaseFile.getParent(), databaseFile.getName() + "-wal");
 if (walFile.exists()) {
  flags |= SQLiteDatabaseCompat.ENABLE_WRITE_AHEAD_LOGGING;
 }
 return flags;
}

代码示例来源:origin: Tencent/tinker

/**
 * @param fromFile
 * @param toPath
 * @param fileCopyProcessor
 */
private static void copyFileToPath(final String fromFile, final String toPath, final FileCopyProcessor fileCopyProcessor) {
  File from = new File(fromFile);
  File to = new File(toPath);
  if (from.exists() && from.isFile()) {
    createDirectory(toPath);
    String tempFromFile = from.getAbsolutePath();
    String tempToFile = to.getAbsolutePath() + File.separator + from.getName();
    copyFileToFile(tempFromFile, tempToFile, fileCopyProcessor);
  }
}

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

private static void validateCreateOutputDir(File dir) {
  if (!dir.exists()) {
    dir.mkdirs();
  }
  if (!dir.canWrite()) {
    throw new IllegalStateException(dir.getName() + " does not have write permissions.");
  }
  if (!dir.isDirectory()) {
    throw new IllegalStateException(dir.getName() + " is not a directory.");
  }
}

代码示例来源: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

String path = Environment.getExternalStorageDirectory().toString()+"/Pictures";
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
  Log.d("Files", "FileName:" + files[i].getName());
}

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

File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getName());

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

private URLClassLoader buildClassLoader(String plugin)
    throws Exception
{
  File file = new File(plugin);
  if (file.isFile() && (file.getName().equals("pom.xml") || file.getName().endsWith(".pom"))) {
    return buildClassLoaderFromPom(file);
  }
  if (file.isDirectory()) {
    return buildClassLoaderFromDirectory(file);
  }
  return buildClassLoaderFromCoordinates(plugin);
}

代码示例来源:origin: Tencent/tinker

/**
 * @param output unsigned apk file output
 * @throws IOException
 */
private void generateUnsignedApk(File output) throws IOException {
  Logger.d("Generate unsigned apk: %s", output.getName());
  final File tempOutDir = config.mTempResultDir;
  if (!tempOutDir.exists()) {
    throw new IOException(String.format(
      "Missing patch unzip files, path=%s\n", tempOutDir.getAbsolutePath()));
  }
  FileOperation.zipInputDir(tempOutDir, output, null);
  if (!output.exists()) {
    throw new IOException(String.format(
      "can not found the unsigned apk file path=%s",
      output.getAbsolutePath()));
  }
}

代码示例来源:origin: Tencent/tinker

private void unzipApkFile(File file, File destFile) throws TinkerPatchException, IOException {
  String apkName = file.getName();
  if (!apkName.endsWith(TypedValue.FILE_APK)) {
    throw new TinkerPatchException(
      String.format("input apk file path must end with .apk, yours %s\n", apkName)
    );
  }
  String destPath = destFile.getAbsolutePath();
  Logger.d("UnZipping apk to %s", destPath);
  FileOperation.unZipAPk(file.getAbsoluteFile().getAbsolutePath(), destPath);
}

代码示例来源:origin: lets-blade/blade

/**
 * Filter the file rules
 *
 * @param file
 * @param recursive
 * @return
 */
private File[] accept(File file, final boolean recursive) {
  // Custom filtering rules If you can loop (include subdirectories) or is the end of the file. Class (compiled java class file)
  return file.listFiles(file1 -> (recursive && file1.isDirectory()) || (file1.getName().endsWith(".class")));
}

代码示例来源:origin: ReactiveX/RxJava

void check(String baseClassName) throws Exception {
  File f = directoryOf(baseClassName);
  if (f == null) {
    return;
  }
  StringBuilder e = new StringBuilder();
  File[] files = f.listFiles();
  if (files != null) {
    for (File g : files) {
      if (g.getName().startsWith(baseClassName) && g.getName().endsWith(".java")) {
        String className = "io.reactivex.internal.operators." + baseClassName.toLowerCase() + "." + g.getName().replace(".java", "");
        Class<?> clazz = Class.forName(className);
        if ((clazz.getModifiers() & Modifier.FINAL) == 0 && (clazz.getModifiers() & Modifier.ABSTRACT) == 0) {
          e.append("java.lang.RuntimeException: ").append(className).append(" is not final\r\n");
          e.append(" at ").append(className).append(" (").append(g.getName()).append(":14)\r\n\r\n");
        }
      }
    }
  }
  if (e.length() != 0) {
    System.out.println(e);
    throw new AssertionError(e.toString());
  }
}

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

@Override
 public boolean accept(File pathname)
 {
  return pathname.exists()
      && pathname.isFile()
      && (pattern == null || pattern.matcher(pathname.getName()).matches());
 }
}

代码示例来源:origin: facebook/stetho

public void cleanupFiles() {
 for (File file : mContext.getFilesDir().listFiles()) {
  if (file.getName().startsWith(FILENAME_PREFIX)) {
   if (!file.delete()) {
    LogRedirector.w(TAG, "Failed to delete " + file.getAbsolutePath());
   }
  }
 }
 LogRedirector.i(TAG, "Cleaned up temporary network files.");
}

代码示例来源:origin: eclipse-vertx/vert.x

private static List<JavaFileObject> browseDir(String packageName, File directory) {
 List<JavaFileObject> result = new ArrayList<>();
 for (File childFile : directory.listFiles()) {
  if (childFile.isFile() && childFile.getName().endsWith(CLASS_FILE)) {
   String binaryName = packageName + "." + childFile.getName().replaceAll(CLASS_FILE + "$", "");
   result.add(new CustomJavaFileObject(childFile.toURI(), JavaFileObject.Kind.CLASS, binaryName));
  }
 }
 return result;
}

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

public void listFilesForFolder(final File folder) {
  for (final File fileEntry : folder.listFiles()) {
    if (fileEntry.isDirectory()) {
      listFilesForFolder(fileEntry);
    } else {
      System.out.println(fileEntry.getName());
    }
  }
}

final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);

代码示例来源:origin: skylot/jadx

private List<File> compileClass(Class<?> cls) throws IOException {
  String fileName = cls.getName();
  int end = fileName.indexOf('$');
  if (end != -1) {
    fileName = fileName.substring(0, end);
  }
  fileName = fileName.replace('.', '/') + ".java";
  File file = new File(TEST_DIRECTORY, fileName);
  if (!file.exists()) {
    file = new File(TEST_DIRECTORY2, fileName);
  }
  assertThat("Test source file not found: " + fileName, file.exists(), is(true));
  List<File> compileFileList = Collections.singletonList(file);
  File outTmp = createTempDir("jadx-tmp-classes");
  outTmp.deleteOnExit();
  List<File> files = StaticCompiler.compile(compileFileList, outTmp, withDebugInfo);
  // remove classes which are parents for test class
  files.removeIf(next -> !next.getName().contains(cls.getSimpleName()));
  for (File clsFile : files) {
    clsFile.deleteOnExit();
  }
  return files;
}

相关文章

微信公众号

最新文章

更多