本文整理汇总了Java中java.io.File类的典型用法代码示例。如果您正苦于以下问题:Java File类的具体用法?Java File怎么用?Java File使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
File类属于java.io包,在下文中一共展示了File类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: SmallObjectHeap
import java.io.File; //导入依赖的package包/类
public SmallObjectHeap(final String p_memDumpFile, final Storage p_memory) {
m_memory = p_memory;
File file = new File(p_memDumpFile);
if (!file.exists()) {
throw new MemoryRuntimeException("Cannot create heap from mem dump " + p_memDumpFile + ": file does not exist");
}
RandomAccessFileImExporter importer;
try {
importer = new RandomAccessFileImExporter(file);
} catch (final FileNotFoundException e) {
// cannot happen
throw new MemoryRuntimeException("Illegal state", e);
}
importer.importObject(this);
}
示例2: mkdirsWithExistsCheck
import java.io.File; //导入依赖的package包/类
/**
* The semantics of mkdirsWithExistsCheck method is different from the mkdirs
* method provided in the Sun's java.io.File class in the following way:
* While creating the non-existent parent directories, this method checks for
* the existence of those directories if the mkdir fails at any point (since
* that directory might have just been created by some other process).
* If both mkdir() and the exists() check fails for any seemingly
* non-existent directory, then we signal an error; Sun's mkdir would signal
* an error (return false) if a directory it is attempting to create already
* exists or the mkdir fails.
* @param dir
* @return true on success, false on failure
*/
public static boolean mkdirsWithExistsCheck(File dir) {
if (dir.mkdir() || dir.exists()) {
return true;
}
File canonDir = null;
try {
canonDir = dir.getCanonicalFile();
} catch (IOException e) {
return false;
}
String parent = canonDir.getParent();
return (parent != null) &&
(mkdirsWithExistsCheck(new File(parent)) &&
(canonDir.mkdir() || canonDir.exists()));
}
示例3: doTestUnpackWAR
import java.io.File; //导入依赖的package包/类
private void doTestUnpackWAR(boolean unpackWARs, boolean unpackWAR,
boolean external, boolean resultDir) throws Exception {
Tomcat tomcat = getTomcatInstance();
StandardHost host = (StandardHost) tomcat.getHost();
host.setUnpackWARs(unpackWARs);
tomcat.start();
File war;
if (unpackWAR) {
war = createWar(WAR_XML_UNPACKWAR_TRUE_SOURCE, !external);
} else {
war = createWar(WAR_XML_UNPACKWAR_FALSE_SOURCE, !external);
}
if (external) {
createXmlInConfigBaseForExternal(war);
}
host.backgroundProcess();
File dir = new File(host.getAppBase(), APP_NAME.getBaseName());
Assert.assertEquals(
Boolean.valueOf(resultDir), Boolean.valueOf(dir.isDirectory()));
}
示例4: processSubFiles
import java.io.File; //导入依赖的package包/类
private void processSubFiles(File file, ProcessSubAIDLFileCallback callback) {
if (file == null) {
return;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for (File f : files) {
processSubFiles(f, callback);
}
}
} else {
if (callback.matchFile(file)) {
callback.processFile(file);
}
}
}
示例5: generateZip
import java.io.File; //导入依赖的package包/类
/**
* Generates a zip file.
*
* @param source source file or directory to compress.
* @param destination destination of zipped file.
* @return the zipped file.
*/
private void generateZip (File source, File destination) throws IOException
{
if (source == null || !source.exists ())
{
throw new IllegalArgumentException ("source file should exist");
}
if (destination == null)
{
throw new IllegalArgumentException (
"destination file should be not null");
}
FileOutputStream output = new FileOutputStream (destination);
ZipOutputStream zip_out = new ZipOutputStream (output);
zip_out.setLevel (
cfgManager.getDownloadConfiguration ().getCompressionLevel ());
List<QualifiedFile> file_list = getFileList (source);
byte[] buffer = new byte[BUFFER_SIZE];
for (QualifiedFile qualified_file : file_list)
{
ZipEntry entry = new ZipEntry (qualified_file.getQualifier ());
InputStream input = new FileInputStream (qualified_file.getFile ());
int read;
zip_out.putNextEntry (entry);
while ((read = input.read (buffer)) != -1)
{
zip_out.write (buffer, 0, read);
}
input.close ();
zip_out.closeEntry ();
}
zip_out.close ();
output.close ();
}
示例6: zipFile
import java.io.File; //导入依赖的package包/类
/**
* Zips the specified file.
* @param file The file to archive.
* @param destinationZipArchive Specifies the zip archive where to store the specified
* file. If the zip archive already exists, it is deleted before starting
* the process. Folders and subfolders are created if needed. If the specified file
* already exists and it is a folder, an exception is raised.
* @param moveFile If <i>true</i> the specified file is deleted from its original
* location after the zip archive has been successfully created.
*/
public static void zipFile(File file,File destinationZipArchive,boolean moveFile) throws Exception {
try {
ArrayList<File> list=new ArrayList<File>();
list.add(file);
zipFiles(list,destinationZipArchive,moveFile);
}
catch (Exception e) {
String sFile="null";
if (file!=null) sFile=file.getAbsolutePath();
String sDestinationZipArchive="null";
if (destinationZipArchive!=null) sDestinationZipArchive=destinationZipArchive.getAbsolutePath();
throw new Exception(ParseError.parseError("ZipHelper.zipFile('"+sFile+"','"+sDestinationZipArchive+"',"+moveFile,e));
}
}
示例7: setOfflineFilePath
import java.io.File; //导入依赖的package包/类
/**
* Sets offline file path.
*
* @param newPath the new path
* @return the offline file path
*/
public synchronized static boolean setOfflineFilePath( String newPath )
{
if ( !newPath.endsWith( "/" ) )
{
newPath = newPath + "/";
}
File newTarget = new File( newPath );
if ( !newTarget.exists() || !newTarget.isDirectory() )
{
return false;
}
OFFLINE_FILE_PATH = newPath;
return true;
}
示例8: testResources
import java.io.File; //导入依赖的package包/类
public void testResources() throws Exception { // #208816
TestFileUtils.writeFile(d,
"pom.xml",
"<project xmlns='http://maven.apache.org/POM/4.0.0'>" +
"<modelVersion>4.0.0</modelVersion>" +
"<groupId>grp</groupId>" +
"<artifactId>art</artifactId>" +
"<packaging>jar</packaging>" +
"<version>0</version>" +
"</project>");
FileObject res = FileUtil.createFolder(d, "src/main/resources");
FileObject tres = FileUtil.createFolder(d, "src/test/resources");
CharSequence log = Log.enable(BinaryForSourceQuery.class.getName(), Level.FINE);
File repo = EmbedderFactory.getProjectEmbedder().getLocalRepositoryFile();
File art0 = new File(repo, "grp/art/0/art-0.jar");
URL url0 = FileUtil.getArchiveRoot(art0.toURI().toURL());
assertEquals(Arrays.asList(new URL(d.toURL(), "target/classes/"), url0), Arrays.asList(BinaryForSourceQuery.findBinaryRoots(res.toURL()).getRoots()));
assertEquals(Arrays.asList(new URL(d.toURL(), "target/test-classes/"), url0), Arrays.asList(BinaryForSourceQuery.findBinaryRoots(tres.toURL()).getRoots()));
String logS = log.toString();
assertFalse(logS, logS.contains("-> nil"));
assertTrue(logS, logS.contains("ProjectBinaryForSourceQuery"));
}
示例9: readProperties
import java.io.File; //导入依赖的package包/类
private Properties readProperties(Vector <? extends Property> antProperties) throws IOException {
Properties props = new Properties();
for(Property prop : antProperties) {
if(prop.getName()!=null) {
if(prop.getValue()!=null) {
props.setProperty(prop.getName(), prop.getValue());
} else if(prop.getLocation()!=null) {
props.setProperty(prop.getName(),
new File(prop.getLocation().getFileName()).getAbsolutePath());
}
} else if(prop.getFile()!=null || prop.getUrl()!=null) {
InputStream is = null;
try {
is = (prop.getFile()!=null) ?
new FileInputStream(prop.getFile()) :
prop.getUrl().openStream();
Properties loadedProps = new Properties();
loadedProps.load(is);
is.close();
if ( prop.getPrefix() != null ) {
for(Object p : loadedProps.keySet()) {
props.setProperty(prop.getPrefix() + p,
loadedProps.getProperty(p.toString()));
}
} else {
props.putAll(loadedProps);
}
} finally {
if (is != null) {
is.close();
}
}
}
}
return props;
}
示例10: testCheckoutFilesFromIndexFileToFolder
import java.io.File; //导入依赖的package包/类
public void testCheckoutFilesFromIndexFileToFolder () throws Exception {
File folder = new File(workDir, "folder");
File subFolder = new File(folder, "folder");
File file1 = new File(subFolder, "file2");
subFolder.mkdirs();
write(file1, "file 1 content");
File[] files = new File[] { folder };
add(files);
commit(files);
file1.delete();
subFolder.delete();
folder.delete();
write(folder, "blabla");
GitClient client = getClient(workDir);
Map<File, GitStatus> statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
assertStatus(statuses, workDir, file1, true, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_REMOVED, GitStatus.Status.STATUS_REMOVED, false);
client.checkout(new File[] { folder }, null, true, NULL_PROGRESS_MONITOR);
statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
assertStatus(statuses, workDir, file1, true, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, GitStatus.Status.STATUS_NORMAL, false);
assert(file1.isFile());
assertEquals("file 1 content", read(file1));
}
示例11: testInitNextRecordReader
import java.io.File; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void testInitNextRecordReader() throws IOException{
JobConf conf = new JobConf();
Path[] paths = new Path[3];
long[] fileLength = new long[3];
File[] files = new File[3];
LongWritable key = new LongWritable(1);
Text value = new Text();
try {
for(int i=0;i<3;i++){
fileLength[i] = i;
File dir = new File(outDir.toString());
dir.mkdir();
files[i] = new File(dir,"testfile"+i);
FileWriter fileWriter = new FileWriter(files[i]);
fileWriter.close();
paths[i] = new Path(outDir+"/testfile"+i);
}
CombineFileSplit combineFileSplit = new CombineFileSplit(conf, paths, fileLength);
Reporter reporter = Mockito.mock(Reporter.class);
CombineFileRecordReader cfrr = new CombineFileRecordReader(conf, combineFileSplit,
reporter, TextRecordReaderWrapper.class);
verify(reporter).progress();
Assert.assertFalse(cfrr.next(key,value));
verify(reporter, times(3)).progress();
} finally {
FileUtil.fullyDelete(new File(outDir.toString()));
}
}
示例12: startDownload
import java.io.File; //导入依赖的package包/类
private void startDownload() {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "ency.apk");
AppFileUtil.delFile(file, true);
// 创建下载任务
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://ucdl.25pp.com/fs08/2017/09/19/10/2_b51f7cae8d7abbd3aaf323a431826420.apk?sf=9946816&vh=1e3a8680ee88002bdf2f00f715146e16&sh=10&cc=3646561943&appid=7060083&packageid=400525966&md5=27456638a0e6615fb5153a7a96c901bf&apprd=7060083&pkg=com.taptap&vcode=311&fname=TapTap&pos=detail-ndownload-com.taptap"));
// 显示下载信息
request.setTitle("Ency");
request.setDescription("新版本下载中");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.setMimeType("application/vnd.android.package-archive");
// 设置下载路径
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "ency.apk");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
// 获取DownloadManager
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
// 将下载请求加入下载队列,加入下载队列后会给该任务返回一个long型的id,通过该id可以取消任务,重启任务、获取下载的文件等等
downloadId = dm.enqueue(request);
Toast.makeText(this, "后台下载中,请稍候...", Toast.LENGTH_SHORT).show();
}
示例13: replayAuditLog
import java.io.File; //导入依赖的package包/类
private static void replayAuditLog() {
System.out.println("\n\nStarting replay with new instance of G10Monitor");
System.out.println("=================================================================================================");
G10Monitor monitor = new G10Monitor();
monitor.registerBreachNotificationHandler(new ConsoleBreachHandler());
monitor.registerResultsReceiver(new OrderBiasResultPrinter());
monitor.registerEventAuditor(new ConsoleAuditor());
CsvAuditReplay replay = new CsvAuditReplay();
/**
* Disable all audit and publishing with:
* monitor.enableAudit(true);
* monitor.enableResultPublication(true);
* monitor.enableResultPublication(true);
*/
replay.replay(monitor, new File("target\\generated-sources\\testlog\\fluxtionfx-audit.log"));
System.out.println("=================================================================================================");
}
示例14: makeFilePath
import java.io.File; //导入依赖的package包/类
/**
* Makes file path if it doesn't exist
**/
public static boolean makeFilePath(File file) {
String parent = file.getParent();
if (parent != null) {
File dir = new File(parent);
try {
if (!dir.exists() && !dir.mkdirs()) {
throw new SecurityException("File.mkdirs() returns false");
}
} catch (SecurityException e) {
Log.w(TAG, e);
return false;
}
}
return true;
}
示例15: updateParticipant
import java.io.File; //导入依赖的package包/类
/**
* 更新 List<Participant> 只更新这一个字段数据
*
* @param tccTransaction 实体对象
*/
@Override
public int updateParticipant(TccTransaction tccTransaction) {
try {
final String fullFileName = RepositoryPathUtils.getFullFileName(filePath,tccTransaction.getTransId());
final File file = new File(fullFileName);
final CoordinatorRepositoryAdapter adapter = readAdapter(file);
if(Objects.nonNull(adapter)){
adapter.setContents(serializer.serialize(tccTransaction.getParticipants()));
}
FileUtils.writeFile(fullFileName,serializer.serialize(adapter));
} catch (Exception e) {
throw new TccRuntimeException("更新数据异常!");
}
return 1;
}