下面列出了怎么用java.io.File的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Opens a stream to the given URI.
* @return Never returns null.
* @throws Throws an InvalidArgumentException for relative URIs. Relative URIs should be
* resolved before being passed into this function.
* @throws Throws an IOException if the URI cannot be opened.
*/
public OutputStream openOutputStream(Uri uri, boolean append) throws IOException {
assertBackgroundThread();
switch (getUriType(uri)) {
case URI_TYPE_FILE: {
File localFile = new File(uri.getPath());
File parent = localFile.getParentFile();
if (parent != null) {
parent.mkdirs();
}
return new FileOutputStream(localFile, append);
}
case URI_TYPE_CONTENT:
case URI_TYPE_RESOURCE: {
AssetFileDescriptor assetFd = contentResolver.openAssetFileDescriptor(uri, append ? "wa" : "w");
return assetFd.createOutputStream();
}
}
throw new FileNotFoundException("URI not supported by CordovaResourceApi: " + uri);
}
/**
* Get all the tickets found in the specified file.
*
* @param ticketsFile
* @return - array of tickets found in the specified tickets file
* @throws IOException
* - io exception from reading tickets file
*/
public static synchronized AuthTicket[] getTickets(File ticketsFile)
throws IOException {
AuthTicket[] tickets = EMPTY;
List<Map<String, String>> authList = ticketsFile != null ?
getFileEntries(ticketsFile) : getMemoryEntries(ticketsMap);
if (authList != null) {
List<AuthTicket> ticketList = new ArrayList<AuthTicket>();
for (Map<String, String> map : authList) {
if (map != null) {
String serverAddress = map.get(SERVER_ADDRESS_MAP_KEY);
String userName = map.get(USER_NAME_MAP_KEY);
String ticketValue = map.get(AUTH_VALUE_MAP_KEY);
AuthTicket ticket = new AuthTicket(serverAddress,
userName, ticketValue);
ticketList.add(ticket);
}
}
tickets = ticketList.toArray(new AuthTicket[0]);
}
return tickets;
}
private void collectInformation(String rootClassName) throws ClassNotFoundException {
if (processed.contains(rootClassName)) {
return;
}
File srcFile = sourceProvider.getSourceFile(rootClassName);
processed.add(rootClassName);
TimestampClass timeStampClazz = javaClassLoader.getTimestampClass(rootClassName);
if (timeStampClazz != null) {
if (FileUtils.isFileNewer(srcFile, timeStampClazz.timestamp)) {
compilationNeeded.add(rootClassName);
} else if (!srcFile.exists()) {
throw new ClassNotFoundException(
String.format("Class %s not found. No sources found in file system.", rootClassName));
}
for (String dependencyName : timeStampClazz.dependencies) {
collectInformation(dependencyName);
}
} else {
compilationNeeded.add(rootClassName);
}
}
public void executeUpgrade(AlpineQueryManager qm, Connection connection) throws SQLException {
LOGGER.info("Recreating table PROJECT_PROPERTY");
DbUtil.dropTable(connection, "PROJECT_PROPERTY"); // Will be dynamically recreated
LOGGER.info("Deleting search engine indices");
IndexManager.delete(IndexManager.IndexType.LICENSE);
IndexManager.delete(IndexManager.IndexType.PROJECT);
IndexManager.delete(IndexManager.IndexType.COMPONENT);
IndexManager.delete(IndexManager.IndexType.VULNERABILITY);
LOGGER.info("Deleting Dependency-Check work directory");
try {
final String DC_ROOT_DIR = Config.getInstance().getDataDirectorty().getAbsolutePath() + File.separator + "dependency-check";
FileDeleteStrategy.FORCE.delete(new File(DC_ROOT_DIR));
} catch (IOException e) {
LOGGER.error("An error occurred deleting the Dependency-Check work directory", e);
}
}
/**
* 将输入流写入文件
*
* @param file 文件
* @param is 输入流
* @param append 是否追加在文件末
* @return {@code true}: 写入成功<br>{@code false}: 写入失败
*/
public static boolean writeFileFromIS(File file, final InputStream is, boolean append) {
if (!FileUtils.createOrExistsFile(file) || is == null) return false;
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(file, append));
byte data[] = new byte[1024];
int len;
while ((len = is.read(data, 0, 1024)) != -1) {
os.write(data, 0, len);
}
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
CloseUtils.closeIO(is, os);
}
}
private static void generateUTF8OutFile(File FinalOutFile) throws IOException
{
if (generateUTF8Out)
{
keepfiles=true;
File UTF8OutFile = new File(UTF8OutName);
// start reading the .out file back in, using default encoding
BufferedReader inFile = new BufferedReader(new FileReader(FinalOutFile));
FileOutputStream fos = new FileOutputStream(UTF8OutFile);
BufferedWriter bw = new BufferedWriter (new OutputStreamWriter(fos, "UTF-8"));
int c;
while ((c = inFile.read()) != -1)
bw.write(c);
bw.flush();
bw.close();
fos.close();
}
}
private static String extractDatabase(Context context) {
try {
File external = context.getExternalFilesDir(null);
File data = Environment.getDataDirectory();
if (external != null && external.canWrite()) {
String dataDBPath = "data/" + context.getPackageName() + "/databases/chuck.db";
String extractDBPath = "chuckdb.temp";
File dataDB = new File(data, dataDBPath);
File extractDB = new File(external, extractDBPath);
if (dataDB.exists()) {
FileChannel in = new FileInputStream(dataDB).getChannel();
FileChannel out = new FileOutputStream(extractDB).getChannel();
out.transferFrom(in, 0, in.size());
in.close();
out.close();
return extractDB.getAbsolutePath();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static void recoverFromKVFile(File file) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while (true) {
String topic = reader.readLine();
if (topic == null) return;
String key = reader.readLine();
if (key == null) return;
long hashId = Long.valueOf(reader.readLine());
int partition = Integer.valueOf(reader.readLine());
String tag = reader.readLine();
String value = reader.readLine();
Result result = recoverProducer.sendWithPartition(topic, partition, hashId, value, key, tag);
LOGGER.info("result={}.topic={},key={},hashId={},partition={},tag={},value.len={}",
result, topic, key, hashId, partition, tag, value.length());
}
}
private void share() {
LumberYard.getInstance(getContext())
.save(new LumberYard.OnSaveLogListener() {
@Override
public void onSave(File file) {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
Intents.maybeStartActivity(getContext(), sendIntent);
}
@Override
public void onError(String message) {
Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
}
});
}
@Test (enabled=false)
public void testStrongEncryptionAndDecryption() throws IOException {
String password = UUID.randomUUID().toString();
String masterPassword = UUID.randomUUID().toString();
File masterPwdFile = getMasterPwdFile(masterPassword);
State state = new State();
state.setProp(ConfigurationKeys.ENCRYPT_KEY_LOC, masterPwdFile.toString());
state.setProp(ConfigurationKeys.ENCRYPT_USE_STRONG_ENCRYPTOR, true);
try{
StrongTextEncryptor encryptor = new StrongTextEncryptor();
encryptor.setPassword(masterPassword);
String encrypted = encryptor.encrypt(password);
encrypted = "ENC(" + encrypted + ")";
String decrypted = PasswordManager.getInstance(state).readPassword(encrypted);
Assert.assertEquals(decrypted, password);
}
catch (EncryptionOperationNotPossibleException e) {
//no strong encryption is supported
}
}
/**
* Get the data from the class file for the specified class. If
* the file can't be found, or the class is not one of the
* special ones listed below, return null.
* Bug4179766Class
* Bug4179766Resource
*/
private byte[] getClassData(String className) {
boolean shouldLoad = className.equals("Bug4179766Class");
shouldLoad = shouldLoad || className.equals("Bug4179766Resource");
if (shouldLoad) {
try {
File file = new File(System.getProperty("test.classes", "."), className+CLASS_SUFFIX);
FileInputStream fi = new FileInputStream(file);
byte[] result = new byte[fi.available()];
fi.read(result);
return result;
} catch (Exception e) {
return null;
}
} else {
return null;
}
}
/**
* User not found
*/
@Test
public void shouldSee404AfterTestEndpointParameters() {
BigDecimal number = null;
Double _double = null;
String patternWithoutDelimiter = null;
byte[] _byte = null;
Integer integer = null;
Integer int32 = null;
Long int64 = null;
Float _float = null;
String string = null;
File binary = null;
LocalDate date = null;
OffsetDateTime dateTime = null;
String password = null;
String paramCallback = null;
api.testEndpointParameters()
.numberForm(number)
._doubleForm(_double)
.patternWithoutDelimiterForm(patternWithoutDelimiter)
._byteForm(_byte).execute(r -> r.prettyPeek());
// TODO: test validations
}
public static void removeAllUserHistoryDictionaries(final Context context) {
synchronized (sLangUserHistoryDictCache) {
for (final ConcurrentHashMap.Entry<String, SoftReference<UserHistoryDictionary>> entry
: sLangUserHistoryDictCache.entrySet()) {
if (entry.getValue() != null) {
final UserHistoryDictionary dict = entry.getValue().get();
if (dict != null) {
dict.clear();
}
}
}
sLangUserHistoryDictCache.clear();
final File filesDir = context.getFilesDir();
if (filesDir == null) {
Log.e(TAG, "context.getFilesDir() returned null.");
return;
}
final boolean filesDeleted = FileUtils.deleteFilteredFiles(
filesDir, new DictFilter(UserHistoryDictionary.NAME));
if (!filesDeleted) {
Log.e(TAG, "Cannot remove dictionary files. filesDir: " + filesDir.getAbsolutePath()
+ ", dictNamePrefix: " + UserHistoryDictionary.NAME);
}
}
}
/**
* 拷贝so库,每次新安装插件覆盖更新原来的so库
*/
private static boolean findAndCopyNativeLib(Context context, ZipFile apk, String cpuArch, String libDir) {
PluginDebugLog.installFormatLog(TAG, "findAndCopyNativeLib start to extract native lib for ABI: %s", cpuArch);
boolean installResult = false;
Enumeration<? extends ZipEntry> entries = apk.entries();
ZipEntry entry;
while (entries.hasMoreElements()) {
entry = entries.nextElement();
String name = entry.getName();
if (!name.startsWith(APK_LIB_DIR_PREFIX + cpuArch)
|| !name.endsWith(APK_LIB_SUFFIX)) {
continue;
}
InputStream entryInputStream = null;
try {
entryInputStream = apk.getInputStream(entry);
String libName = name.substring(name.lastIndexOf("/") + 1);
PluginDebugLog.installFormatLog(TAG, "libDir: %s, soFileName: %s", libDir, libName);
File libFile = new File(libDir, libName);
if (libFile.exists()) {
PluginDebugLog.installFormatLog(TAG, "soFileName: %s already exist, delete it", libName);
libFile.delete();
}
// copy zip entry to lib dir
installResult = copyToFile(entryInputStream, libFile);
} catch (Exception e) {
// ignore
} finally {
closeQuietly(entryInputStream);
}
}
return installResult;
}
@Test
public void testCorrectsAssemblyArchive() throws Exception {
File installMarker = new File("liberty/wlp", ".installed");
assertTrue("install marker " + installMarker.getCanonicalFile() + " doesn't exist", installMarker.exists());
String expectedRuntimeVersion = System.getProperty("libertyRuntimeVersion");
String assemblyArchivePath = FileUtils.readFileToString(installMarker);
assertTrue("assembly archive path " + assemblyArchivePath + " does not contain expected runtime version " + expectedRuntimeVersion,
assemblyArchivePath.contains(expectedRuntimeVersion));
}
public BeakerXJsonConfig() {
this(Paths.get((
System.getenv("JUPYTER_CONFIG_DIR") != null
? System.getenv("JUPYTER_CONFIG_DIR")
: (System.getProperty("user.home") + File.separator + ".jupyter"))
+ File.separator + "beakerx.json"));
}
public static void exportDiskStore(ArrayList<String> args, String outputDir) {
File out = outputDir == null ? new File(".") : new File(outputDir);
if (!out.exists()) {
out.mkdirs();
}
String dsName = args.get(0);
File[] dirs = argsToFile(args.subList(1, args.size()));
try {
DiskStoreImpl.exportOfflineSnapshot(dsName, dirs, out);
} catch (Exception ex) {
throw new GemFireIOException(" disk-store=" + dsName + ": " + ex, ex);
}
}
/**
* Compare jps output with a content in a file line by line
*/
public static void verifyOutputAgainstFile(OutputAnalyzer output) throws IOException {
String testSrc = System.getProperty("test.src", "?");
File file = new File(testSrc, "usage.out");
List<String> fileOutput = Utils.fileAsList(file);
List<String> outputAsLines = output.asLines();
assertTrue(outputAsLines.containsAll(fileOutput),
"The ouput should contain all content of " + file.getAbsolutePath());
}
@Override
protected void bindViewHolder(Cursor cursor, MediaRecyclerViewAdapter.ViewHolder holder) {
if (!S.isValidContextForGlide(holder.itemView.getContext()))
return;
final long imgId = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID));
Cursor thumbnailCursor =
MediaStore.Images.Thumbnails.queryMiniThumbnail(
getContentResolver(),
imgId,
MediaStore.Images.Thumbnails.MINI_KIND,
null);
if (thumbnailCursor != null && thumbnailCursor.getCount() > 0 && thumbnailCursor.moveToFirst() && new File(thumbnailCursor.getString(thumbnailCursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA))).exists()) {
Glide
.with(holder.itemView)
.load(thumbnailCursor.getString(thumbnailCursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA)))
.apply(requestOptions)
.into(holder.pic);
} else {
thumbnailCursor = MediaStore.Images.Thumbnails.queryMiniThumbnail(getContentResolver(), imgId, MediaStore.Images.Thumbnails.MICRO_KIND, null);
if (thumbnailCursor != null && thumbnailCursor.getCount() > 0 && thumbnailCursor.moveToFirst() && new File(thumbnailCursor.getString(thumbnailCursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA))).exists()) {
Glide
.with(this)
.load(thumbnailCursor.getString(thumbnailCursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA)))
.apply(requestOptions)
.into(holder.pic);
} else {
Glide
.with(this)
.load(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)))
.apply(requestOptions)
.into(holder.pic);
}
}
if (thumbnailCursor != null)
thumbnailCursor.close();
}
public File createTempFile(String name) throws CacheException {
try {
return File.createTempFile(
String.format("ac-%1$s-temp-%s-", Config.getInstance().getDeviceName(), name),
".tmp",
folder);
}
catch (IOException e) {
throw new CacheException("Unable to create temporary file in cache.", e);
}
}
/**
* Dump an overview shapefile for a las folder.
*
* @param folder the folder.
* @param crs the crs to use.
* @throws Exception
*/
public static void dumpLasFolderOverview( String folder, CoordinateReferenceSystem crs ) throws Exception {
SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
b.setName("overview");
b.setCRS(crs);
b.add("the_geom", Polygon.class);
b.add("name", String.class);
SimpleFeatureType type = b.buildFeatureType();
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
OmsFileIterator iter = new OmsFileIterator();
iter.inFolder = folder;
iter.fileFilter = new FileFilter(){
public boolean accept( File pathname ) {
return pathname.getName().endsWith(".las");
}
};
iter.process();
List<File> filesList = iter.filesList;
for( File file : filesList ) {
try (ALasReader r = new LasReaderBuffered(file, crs)) {
r.open();
ReferencedEnvelope3D envelope = r.getHeader().getDataEnvelope();
Polygon polygon = GeometryUtilities.createPolygonFromEnvelope(envelope);
Object[] objs = new Object[]{polygon, r.getLasFile().getName()};
builder.addAll(objs);
SimpleFeature feature = builder.buildFeature(null);
newCollection.add(feature);
}
}
File folderFile = new File(folder);
File outFile = new File(folder, "overview_" + folderFile.getName() + ".shp");
OmsVectorWriter.writeVector(outFile.getAbsolutePath(), newCollection);
}
public static void compressImageToFile(Bitmap bmp,File file) {
int options = 100;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Main method of compress the file
*
* @param file origin file
* @param out compressed file stream
* @param baseDir file path
*/
private static void zip(File file,ZipOutputStream out,String baseDir)
{
if (file.isDirectory()) {
logger.info("Compress dir:"+baseDir+file.getName());
zipDirectory(file, out, baseDir);
} else {
logger.info("Compress file:"+baseDir+file.getName());
zipSingleFile(file, out, baseDir);
}
}
/**
* Adds the given file into filesUnderRoot:
* <ul>
* <li>if the file was already in the set, does nothing and returns true</li>
* <li>if the file lies under a folder already present in the set, does nothing and returns true</li>
* <li>if the file and none of it's ancestors is not in the set yet, this adds the file into the set,
* removes all it's children and returns false</li>
* @param repository repository root
* @param filesUnderRoot set of repository roots
* @param file file to add
* @return false if the file was added or true if it was already contained
*/
public static boolean prepareRootFiles (File repository, Collection<File> filesUnderRoot, File file) {
boolean added = false;
Set<File> filesToRemove = new HashSet<File>();
for (File fileUnderRoot : filesUnderRoot) {
if (file.equals(fileUnderRoot) || fileUnderRoot.equals(repository)) {
// file has already been inserted or scan is planned for the whole repository root
added = true;
break;
}
if (file.equals(repository)) {
// plan the scan for the whole repository root
// adding the repository, there's no need to leave all other files
filesUnderRoot.clear();
break;
} else {
if (file.getAbsolutePath().length() < fileUnderRoot.getAbsolutePath().length()) {
if (Utils.isAncestorOrEqual(file, fileUnderRoot)) {
filesToRemove.add(fileUnderRoot);
}
} else {
if (Utils.isAncestorOrEqual(fileUnderRoot, file)) {
added = true;
break;
}
}
}
}
filesUnderRoot.removeAll(filesToRemove);
if (!added) {
// not added yet
filesUnderRoot.add(file);
}
return added;
}
/**
* Create FileSpec without the originalPath. Verify the
* error in the getInvalidFileSpecs() info.
*/
@Test
public void testFileSpecGetInvalidFileSpecsNoPath() throws Exception {
IServer server = null;
int expNumValidFSpecs = 1;
int expNumInvalidFSpecs = 0;
debugPrintTestName();
//create the files
String sourceFile = clientRoot + File.separator + textBaseFile;
String newFile = clientRoot + File.separator + clientDir + File.separator + "testfileFSpec.txt";
String newFilePath = clientRoot + File.separator + clientDir;
File file1 = new File(newFilePath + File.separator + prepareTestFile(sourceFile, newFile, true));
//create the filePaths
final String[] filePaths = {
file1.getAbsolutePath(),
};
//set up the expected values
VerifyFileSpec fSpec0 = new VerifyFileSpec();
fSpec0.setExpClientName(defaultTestClientName);
fSpec0.setExpUserName(userName);
fSpec0.setExpFileType(P4JTEST_FILETYPE_TEXT);
fSpec0.setExpOpStatus(FileSpecOpStatus.VALID);
//now build the spec without specifying the original filepath
List<IFileSpec> buildFileSpecs = buildFileSpecs(filePaths, fSpec0);
dumpFileSpecInfo(buildFileSpecs, "Built file Specs");
dumpFileSpecMethods(buildFileSpecs.get(0), "Built file Specs");
assertEquals("Number of valid fileSpecs is incorrect.", expNumValidFSpecs, FileSpecBuilder.getValidFileSpecs(buildFileSpecs).size());
assertEquals("Number of invalid fileSpecs is incorrect.", expNumInvalidFSpecs, FileSpecBuilder.getInvalidFileSpecs(buildFileSpecs).size());
}
/**
* Here we check if the file is an image, and if thus if we should create views corresponding
* to our image layouts.
*
* @param position 0 - n, where the header has been subtracted
* @param file to check type of
* @return the viewtype of the item
*/
@Override
public int getItemViewType(int position, @NonNull File file) {
if (isMultimedia(file)) {
if (isCheckable(file)) {
return VIEWTYPE_IMAGE_CHECKABLE;
} else {
return VIEWTYPE_IMAGE;
}
} else {
return super.getItemViewType(position, file);
}
}
public static Intent getFileIntent(String filePath, String fileType) {
File file = new File(filePath);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = FileProvider.getUriForFile(Utils.getContext(),
Utils.getContext().getPackageName() + ".pdFileProvider", file);
intent.setDataAndType(uri, TextUtils.isEmpty(fileType) ? getFileType(filePath) : fileType);
return intent;
}
private MimeMessagePreparator prepareTemplateBuildMimeMessagePreparator(String from, List<String> to, String subject, String mailMessageUrlOrBody, Map<String, Object> templateModelValues, final String attachmentUrl, final Boolean isPlainMessage) {
MimeMessagePreparator messagePreparator = mimeMessage -> {
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
messageHelper.setFrom(from);
String[] toMailList = to.toArray(new String[to.size()]);
messageHelper.setTo(toMailList);
messageHelper.setSubject(subject);
if(StringUtils.isNotEmpty(attachmentUrl) && isHttpUrl(attachmentUrl)) {
URL url = new URL(attachmentUrl);
String filename = url.getFile();
byte fileContent [] = getFileContent(url);
messageHelper.addAttachment(filename, new ByteArrayResource(fileContent));
}
String content = StringUtils.EMPTY;
if(isPlainMessage) {
content = mailContentBuilderService.buildPlainTextMail(mailMessageUrlOrBody, templateModelValues);
} else {
if(!isHttpUrl(mailMessageUrlOrBody)) {
File template = new ClassPathResource("templates/".concat(mailMessageUrlOrBody).concat(".html")).getFile();
content = mailContentBuilderService.buildPlainTextMail(FileUtils.readFileToString(template, "UTF-8"), templateModelValues);
} else {
content = processTemplate(mailMessageUrlOrBody, templateModelValues);
}
}
messageHelper.setText(content, true);
};
return messagePreparator;
}
@Override
public long getContainerUsableSpace(String containerName) throws IOException {
Map<String, File> map = configuration.getStorageDirectories();
File container = map.get(containerName);
if(container != null) {
return FileUtils.getContainerUsableSpace(container.toPath());
} else {
throw new IllegalArgumentException("There is no defined container with name " + containerName);
}
}
private boolean writeCalendarFile(final Calendar calendar, final String calType, final String calId) {
final File fCalendarFile = getCalendarFile(calType, calId);
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(fCalendarFile, false));
final CalendarOutputter calOut = new CalendarOutputter(false);
calOut.output(calendar, os);
} catch (final Exception e) {
return false;
} finally {
FileUtils.closeSafely(os);
}
return true;
}