Java File.exists方法示例大全
下文笔者讲述file.exists方法的功能及示例大全,如下所示
File.exists方法的功能
用于判断路径是否存在 即用于判断一个路径对应的文件或文件夹是否存在 注意事项: File.exists是一个静态方法 他属于java.io.File包,使用时,需先导入java.io.File包例
检测文件是否有效
import java.io.File; protected boolean ensureTargetFileIsValid(File targetFile) { if (targetFile.exists() && targetFile.isDirectory()) { displayErrorDialog(N4ExportMessages.Export_mustBeFile); giveFocusToDestination(); return false; } if (targetFile.exists()) { if (targetFile.canWrite()) { if (!this.overwriteExistingFilesCheckbox.getSelection() && !queryYesNoQuestion(N4ExportMessages.Export_alreadyExists)) { return false; } } else { displayErrorDialog(N4ExportMessages.Export_alreadyExistsError); giveFocusToDestination(); return false; } } return true; }
createFromArchetype
import java.io.File; //导入方法依赖的package包/类 public static void createFromArchetype(File projDir, ProjectInfo vi, Archetype arch, @NullAllowed Map<String,String> additional, boolean updateLastUsedProjectDir) throws IOException { final File parent = projDir.getParentFile(); if (parent == null) { throw new IOException("no parent of " + projDir); } if (updateLastUsedProjectDir && parent != null && parent.exists()) { ProjectChooser.setProjectsFolder(parent); } if (!parent.isDirectory() && !parent.mkdirs()) { throw new IOException("could not create " + parent); } runArchetype(parent, vi, arch, additional); }
databaseExists
import java.io.File; //导入方法依赖的package包/类 /** * Checks if the given database exists in the Derby system home * @return true if the database exists, false otherwise * @throws NullPointerException if <code>databaseName</code> is null. */ public boolean databaseExists(String databaseName) { if (databaseName == null) { throw new NullPointerException("The databaseName parameter cannot be null"); // NOI18N } // just because it makes sense, not really needed anywhere probably if ("".equals(databaseName)) { // NOI18N return false; } String systemHome = DerbySupport.getSystemHome(); if (systemHome.length() <= 0) { // NOI18N return false; } File databaseFile = new File(systemHome, databaseName); return databaseFile.exists(); }
findLibrary
import java.io.File; //导入方法依赖的package包/类 /** * Finds a native library. This method is called after the parent * ClassLoader has failed to find a native library of the same name. * * @param libname The name of the library to find * @return the complete path of the library, or {@code null} if the library * is not found. */ @Override protected String findLibrary(String libname) { ensureInit(); String fileName = System.mapLibraryName(libname); for (int i = 0; i < mLibPaths.length; i++) { String pathName = mLibPaths[i] + fileName; File test = new File(pathName); if (test.exists()) { if (VERBOSE_DEBUG) System.out.println(" found " + libname); return pathName; } } if (VERBOSE_DEBUG) System.out.println(" library " + libname + " not found"); return null; }
createNewJarFile
import java.io.File; //导入方法依赖的package包/类 private File createNewJarFile (String prefix) throws IOException { if (prefix == null) { prefix = "modules"; } File dir = new File(this.getWorkDir(), prefix); dir.mkdirs(); int i = 0; for (;;) { File f = new File (dir, i++ + ".jar"); if (!f.exists ()) { f.createNewFile(); return f; } } }
saveOneWithUrlExistNameInDirectory
import java.io.File; //导入方法依赖的package包/类 @Test public void saveOneWithUrlExistNameInDirectory() { Picture picture = pictures.getFirst(); Picture secondPicture = new Picture(picture.getPath(), picture.getName(), picture.getFileType()); service.save(picture, URL); service.save(secondPicture, URL); assertTrue(picture.equals(service.findOne(picture))); assertNull("Error\n(Check your directory, and delete picture with name \"name0\" if exist from last test?)", service.findOne(secondPicture)); File f = new File(picture.getPath() + picture.getName() + picture.getFileType()); if (f.exists() && !f.isDirectory()) service.delete(picture); else fail("the picture wasn't created"); }
generateSaveFile
import java.io.File; //导入方法依赖的package包/类 /** * Creates a filename (where the file should be saved) from info about a * download. */ public String generateSaveFile(String filename, long filesize) throws GenerateSaveFileError { String path = generateTempSaveFileName(filename); File expPath = new File(path); if (!Helpers.isExternalMediaMounted()) { Log.d(Constants.TAG, "External media not mounted: " + path); throw new GenerateSaveFileError(STATUS_DEVICE_NOT_FOUND_ERROR, "external media is not yet mounted"); } if (expPath.exists()) { Log.d(Constants.TAG, "File already exists: " + path); throw new GenerateSaveFileError(STATUS_FILE_ALREADY_EXISTS_ERROR, "requested destination file already exists"); } if (Helpers.getAvailableBytes(Helpers.getFilesystemRoot(path)) < filesize) { throw new GenerateSaveFileError(STATUS_INSUFFICIENT_SPACE_ERROR, "insufficient space on external storage"); } return path; }
delete
import java.io.File; //导入方法依赖的package包/类 /** * delete a file * * @param file */ public static void delete(File file) { if (file != null && file.exists()) { if (file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { for (File child : children) { delete(child); } } file.delete(); } else { file.delete(); } } }
createDiskFile
import java.io.File; //导入方法依赖的package包/类 protected void createDiskFile(MultipartElement element) { File tempFile = element.getFile(); if (tempFile.exists()) { DiskFile theFile = new DiskFile(tempFile.getAbsolutePath()); theFile.setContentType(element.getContentType()); theFile.setFileName(element.getFileName()); theFile.setFileSize((int) tempFile.length()); fileElements.put(element.getName(), theFile); allElements.put(element.getName(), theFile); } }
create
import java.io.File; //导入方法依赖的package包/类 public static Builder create(Context context) { File file = new File(context.getExternalFilesDir("").getParentFile(), "cache"); if (file != null && !file.exists()) { file.mkdirs(); } UpdateUtil.log("===>>> " + context.getExternalCacheDir()); return new Builder(context).setWifiOnly(sIsWifiOnly); }
upZipFile
import java.io.File; //导入方法依赖的package包/类 /** * 解压缩一个文件 * * @param zipFile 压缩文件 * @param folderPath 解压缩的目标目录 * @throws IOException 当解压缩过程出错时抛出 */ public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException { File desDir = new File(folderPath); if (!desDir.exists()) { desDir.mkdirs(); } ZipFile zf = new ZipFile(zipFile); for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements(); ) { ZipEntry entry = ((ZipEntry) entries.nextElement()); InputStream in = zf.getInputStream(entry); String str = folderPath + File.separator + entry.getName(); str = new String(str.getBytes("8859_1"), "GB2312"); File desFile = new File(str); if (!desFile.exists()) { File fileParentDir = desFile.getParentFile(); if (!fileParentDir.exists()) { fileParentDir.mkdirs(); } desFile.createNewFile(); } OutputStream out = new FileOutputStream(desFile); byte buffer[] = new byte[BUFF_SIZE]; int realLength; while ((realLength = in.read(buffer)) > 0) { out.write(buffer, 0, realLength); } in.close(); out.close(); } }
writeFile
import java.io.File; //导入方法依赖的package包/类 /** * Writes a String to a file. It also adds a note for the user, * * @param file The file to write to. Cannot be null. * @param lines The lines to write. * @throws IOException If something did not work :( */ private void writeFile(File file, String... lines) throws IOException { if (!file.exists()) { file.createNewFile(); } try ( FileWriter fileWriter = new FileWriter(file); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter) ) { for (String line : lines) { bufferedWriter.write(line); bufferedWriter.newLine(); } } }
LocalSyncableOutputStream
import java.io.File; //导入方法依赖的package包/类 public LocalSyncableOutputStream(Path path) throws FileNotFoundException { File dir = new File(path.getParent().toString()); if (!dir.exists()) { boolean success = dir.mkdirs(); if (!success) { throw new FileNotFoundException("failed to create parent directory"); } } fos = new FileOutputStream(path.toString()); output = new BufferedOutputStream(fos, 64*1024); }
start
import java.io.File; //导入方法依赖的package包/类 @Override public Object start(final IApplicationContext context) throws Exception { Object o = context.getArguments().get(IApplicationContext.APPLICATION_ARGS); Display.getDefault(); if (o != null && o instanceof String[]) { String[] args = (String[]) o; for (int i = 0; i < args.length; i++) { if (args[i].equals(DESTINATION_ARG)) { m_directory = new File(args[i + 1]); } else if (args[i].equals(CATEGORY_ARG)) { m_catPath = args[i + 1]; } else if (args[i].equals(PLUGIN_ARG)) { m_pluginIds.add(args[i + 1]); } else if (args[i].equals(INCLUDE_DEPRECATED_ARG)) { m_includeDeprecated = true; } else if (args[i].equals("-help")) { printUsage(); return EXIT_OK; } } } if (m_directory == null) { System.err.println("No output directory specified"); printUsage(); return 1; } else if (!m_directory.exists() && !m_directory.mkdirs()) { System.err.println("Could not create output directory '" + m_directory.getAbsolutePath() + "'."); return 1; } generate(); return EXIT_OK; }
copyTestFile
import java.io.File; //导入方法依赖的package包/类 /** * Copies a file from assets to the device's file system. * @param context * @param srcFilePath the source file path in assets. * @param destFilePath the destination file path. * @throws IllegalStateException if the destination file already exists. */ @SuppressFBWarnings("OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE") private static void copyTestFile(Context context, String srcFilePath, String destFilePath) throws IOException { File destFile = new File(destFilePath); if (destFile.exists()) { throw new IllegalStateException(srcFilePath + " already exists."); } if (!FileUtils.extractAsset(context, srcFilePath, destFile)) { throw new IOException("Could not extract asset " + srcFilePath + "."); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。