下面列出了java.io.File#getPath ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static ArrayList<ProtoFile> listFilesInProject(Project p) {
File f = new File(p.getSandboxPath());
File[] file = f.listFiles();
ArrayList<ProtoFile> protoFiles = new ArrayList<>();
for (File element : file) {
ProtoFile protoFile = new ProtoFile();
protoFile.project_parent = p.getName();
protoFile.name = element.getName();
protoFile.size = element.length();
protoFile.path = element.getPath();
protoFile.type = "file";
protoFiles.add(protoFile);
}
return protoFiles;
}
/**
* 获取磁盘可用空间.
*/
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public static long getSDCardAvailaleSize() {
File path = getRootPath();
StatFs stat = new StatFs(path.getPath());
long blockSize, availableBlocks;
if (Build.VERSION.SDK_INT >= 18) {
blockSize = stat.getBlockSizeLong();
availableBlocks = stat.getAvailableBlocksLong();
} else {
blockSize = stat.getBlockSize();
availableBlocks = stat.getAvailableBlocks();
}
return availableBlocks * blockSize;
}
@Test
public void testAddIncludesToWriter() throws Exception {
AddTransformationCommand command = new AddTransformationCommand("imports-cleaner", "mychain", false, null, null,
null, null, false);
File aux = new File("src/test/resources/xmlincludes");
aux.mkdirs();
File xml = new File(aux, "walkmod.xml");
XMLConfigurationProvider prov = new XMLConfigurationProvider(xml.getPath(), false);
try {
prov.createConfig();
TransformationConfig transfCfg = command.buildTransformationCfg();
prov.addTransformationConfig("mychain", null, transfCfg, false, null, null);
prov.setWriter("mychain", "eclipse-writer", null, false, null);
prov.addIncludesToChain("mychain", Arrays.asList("foo"), false, false, true);
String output = FileUtils.readFileToString(xml);
System.out.println(output);
Assert.assertTrue(output.contains("wildcard") && output.contains("foo"));
} finally {
FileUtils.deleteDirectory(aux);
}
}
private String copy2UploadDir() throws IOException, Exception {
if (!YesNo.YES.equals(this.isFile)) {
return "";
}
File uploadDir = UploadSupportUtils.mkdirUploadFileDir(system, type);
String realFileName = UploadSupportUtils.generateRealFileName(this.uploadFileName);
File realFile = new File( uploadDir.getPath() + "/" + realFileName );
try {
FileUtils.copyFile(this.getUpload(), realFile);
} catch (IOException e) {
throw e;
} finally {
realFile = null;
uploadDir = null;
}
return realFileName;
}
String readableFileName(File f) {
String path = f.getPath();
int firstChar = 0;
for (; firstChar < path.length(); firstChar++) {
if (Character.isLetterOrDigit(path.charAt(firstChar))) {
break;
}
}
if (firstChar == path.length()) {
firstChar = 0;
}
int firstSeg = path.indexOf(File.separatorChar, firstChar);
if (firstSeg > 0) {
return path.substring(firstChar, firstSeg) + "/.../" + f.getName();
}
return f.getName();
}
public void photo() {
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File dir = new File(Environment.getExternalStorageDirectory()
+ "/myimage/");
String fileName = String.valueOf(System.currentTimeMillis())
+ ".jpg";
if (!dir.exists())
dir.mkdir();
File file = new File(dir, fileName);
path = file.getPath();
Uri imageUri = Uri.fromFile(file);
openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(openCameraIntent, TAKE_PICTURE);
}
}
private String findSocketFile(int pid) {
File f = new File(tmpdir, ".java_pid" + pid);
if (!f.exists()) {
return null;
}
return f.getPath();
}
public static String writeTempDexFile(byte[] bytes) {
File file = getTempDexFile();
if (file != null) {
writeRawBytes(file, bytes);
return file.getPath();
}
Log.e("InstantRun", "No file to write temp dex content to");
return null;
}
@Test
public void testRemoveIncludes() throws Exception {
AddTransformationCommand command = new AddTransformationCommand("imports-cleaner", "mychain", false, null, null,
null, null, false);
File aux = new File("src/test/resources/xmlincludes");
if (aux.exists()) {
FileUtils.deleteDirectory(aux);
}
aux.mkdirs();
File xml = new File(aux, "walkmod.xml");
XMLConfigurationProvider prov = new XMLConfigurationProvider(xml.getPath(), false);
try {
prov.createConfig();
TransformationConfig transfCfg = command.buildTransformationCfg();
prov.addTransformationConfig("mychain", null, transfCfg, false, null, null);
prov.setWriter("mychain", "eclipse-writer", null, false, null);
prov.addIncludesToChain("mychain", Arrays.asList("foo"), false, true, false);
prov.removeIncludesFromChain("mychain", Arrays.asList("foo"), false, true, false);
String output = FileUtils.readFileToString(xml);
System.out.println(output);
Assert.assertTrue(!output.contains("wildcard") && !output.contains("foo"));
} finally {
FileUtils.deleteDirectory(aux);
}
}
/**
* Determines whether the caller has write access to the cache directory, stores the result in the
* <code>CacheInfo</code> object, and returns the decision. This method helps to prevent mysterious
* SecurityExceptions to be thrown when this convenience class is used in an applet, for example.
*/
private static boolean hasCachePermission() {
Boolean hasPermission = getCacheInfo().getHasPermission();
if (hasPermission != null) {
return hasPermission.booleanValue();
} else {
try {
SecurityManager security = System.getSecurityManager();
if (security != null) {
File cachedir = getCacheDirectory();
String cachepath;
if (cachedir != null) {
cachepath = cachedir.getPath();
} else {
cachepath = getTempDir();
if (cachepath == null) {
getCacheInfo().setHasPermission(Boolean.FALSE);
return false;
}
}
security.checkWrite(cachepath);
}
} catch (SecurityException e) {
getCacheInfo().setHasPermission(Boolean.FALSE);
return false;
}
getCacheInfo().setHasPermission(Boolean.TRUE);
return true;
}
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
File deirectory = new File(protoPath);
listAllProtoFile(deirectory);
CommonProto2Java protp2ServicePojo = CommonProto2Java.forConfig(protoPath, buildPath);
for (File file : allProtoFile) {
if (file.exists()) {
String protoFilePath = file.getPath();
protp2ServicePojo.generateFile(protoFilePath);
}
}
}
public static void assertXmlFile(final File file, String... xpath)
throws IOException, SAXException {
try {
String xml = FileUtils.readFileToString(file, "UTF-8");
String results = TestHarness.validateXPath(xml, xpath);
if (null != results) {
String msg = "File XPath failure: file=" + file.getPath() + " xpath="
+ results + "\n\nxml was: " + xml;
fail(msg);
}
} catch (XPathExpressionException e2) {
throw new RuntimeException("XPath is invalid", e2);
}
}
private String getFilePath(String file) {
URL url = Thread.currentThread().getContextClassLoader().getResource(file);
if (url == null) {
url = FileConfigLoaderTest.class.getClassLoader().getResource(file);
}
if (url == null) {
File f = Paths.get(file).toFile();
if (f.exists()) {
return f.getPath();
}
} else {
return url.getPath();
}
return null;
}
@Override
protected void install() throws Exception {
File dest = new File(getPluginPath());
dest = dest.getParentFile().getParentFile();
WebConfigurator config = new WebConfigurator(dest.getPath() + "/web.xml");
// config.addServlet("CXFServlet", WebserviceServlet.class.getName());
// config.writeXMLDoc();
config.addServletMapping("CXFServlet", "/app/*");
config.writeXMLDoc();
setRestartRequired();
}
private String findSocketFile(int pid) {
File f = new File(tmpdir, ".java_pid" + pid);
if (!f.exists()) {
return null;
}
return f.getPath();
}
static File compile(File f) {
int rc = com.sun.tools.javac.Main.compile(new String[] {
"-source", "1.8", "-g", f.getPath() });
if (rc != 0)
throw new Error("compilation failed. rc=" + rc);
String path = f.getPath();
return new File(path.substring(0, path.length() - 5) + ".class");
}
protected Map<String, String> createEnvs( String commonToolEnvKey, String platform )
throws NativeBuildException
{
File tmpEnvExecFile = null;
try
{
File vsCommonToolDir = this.getCommonToolDirectory( commonToolEnvKey );
File vsInstallDir = this.getVisualStudioInstallDirectory( vsCommonToolDir );
if ( !vsInstallDir.isDirectory() )
{
throw new NativeBuildException( vsInstallDir.getPath() + " is not a directory." );
}
tmpEnvExecFile = this.createEnvWrapperFile( vsInstallDir, platform );
Commandline cl = new Commandline();
cl.setExecutable( tmpEnvExecFile.getAbsolutePath() );
EnvStreamConsumer stdout = new EnvStreamConsumer();
StreamConsumer stderr = new DefaultConsumer();
CommandLineUtils.executeCommandLine( cl, stdout, stderr );
return stdout.getParsedEnv();
}
catch ( Exception e )
{
throw new NativeBuildException( "Unable to retrieve env", e );
}
finally
{
if ( tmpEnvExecFile != null )
{
tmpEnvExecFile.delete();
}
}
}
/**
* Determines whether the caller has write access to the cache
* directory, stores the result in the <code>CacheInfo</code> object,
* and returns the decision. This method helps to prevent mysterious
* SecurityExceptions to be thrown when this convenience class is used
* in an applet, for example.
*/
private static boolean hasCachePermission() {
Boolean hasPermission = getCacheInfo().getHasPermission();
if (hasPermission != null) {
return hasPermission.booleanValue();
} else {
try {
SecurityManager security = System.getSecurityManager();
if (security != null) {
File cachedir = getCacheDirectory();
String cachepath;
if (cachedir != null) {
cachepath = cachedir.getPath();
} else {
cachepath = getTempDir();
if (cachepath == null || cachepath.isEmpty()) {
getCacheInfo().setHasPermission(Boolean.FALSE);
return false;
}
}
// we have to check whether we can read, write,
// and delete cache files.
// So, compose cache file path and check it.
String filepath = cachepath;
if (!filepath.endsWith(File.separator)) {
filepath += File.separator;
}
filepath += "*";
security.checkPermission(new FilePermission(filepath, "read, write, delete"));
}
} catch (SecurityException e) {
getCacheInfo().setHasPermission(Boolean.FALSE);
return false;
}
getCacheInfo().setHasPermission(Boolean.TRUE);
return true;
}
}
/**
* Prepare all the support resources in one single zip: all the logs, the
* context.properties, the snapshot of the env variables.
*/
private File prepareAllSupportResources(HttpServletRequest request, HttpServletResponse response) {
File tmp = null;
try {
tmp = File.createTempFile("logs", ".zip");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(tmp));
try {
LoggingConfigurator conf = new LoggingConfigurator();
Collection<String> appenders = conf.getLoggingFiles();
/*
* Store the log files in the zip file
*/
for (String appender : appenders) {
if (appender.endsWith("_WEB"))
continue;
File logFile = new File(conf.getFile(appender, true));
writeEntry(out, logFile.getName(), logFile);
}
/*
* Now create a copy of the configuration and store it in the
* zip file
*/
File buf = File.createTempFile("context", ".properties");
ContextProperties cp = Context.get().getProperties();
OrderedProperties prop = new OrderedProperties();
for (String key : cp.getKeys()) {
if (key.contains("password"))
continue;
else
prop.put(key, cp.get(key));
}
prop.store(new FileOutputStream(buf), "Support Request");
writeEntry(out, "context.properties", buf);
FileUtil.strongDelete(buf);
/*
* Now create a file with the environment
*/
String env = SystemUtil.printEnvironment();
buf = File.createTempFile("environment", ".txt");
FileUtil.writeFile(env, buf.getPath());
writeEntry(out, "environment.txt", buf);
FileUtil.strongDelete(buf);
/*
* Discover the tomcat's folder
*/
ServletContext context = getServletContext();
File tomcatFile = new File(context.getRealPath("/WEB-INF/web.xml"));
tomcatFile = tomcatFile.getParentFile().getParentFile().getParentFile().getParentFile();
/*
* Now put the server.xml file
*/
File serverFile = new File(tomcatFile.getPath() + "/conf/server.xml");
writeEntry(out, "tomcat/server.xml", serverFile);
/*
* Now put the most recent tomcat's logs
*/
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String today = df.format(new Date());
File logsDir = new File(tomcatFile.getPath() + "/logs");
File[] files = logsDir.listFiles();
for (File file : files) {
if (file.isDirectory() || (!file.getName().toLowerCase().endsWith(".log")
&& !file.getName().toLowerCase().endsWith(".out")
&& !file.getName().toLowerCase().endsWith(".txt")))
continue;
// store just the logs of today
if (file.getName().toLowerCase().endsWith(".out")
|| file.getName().toLowerCase().endsWith(today + ".log")
|| file.getName().toLowerCase().endsWith(today + ".txt"))
writeEntry(out, "tomcat/" + file.getName(), file);
}
prop.store(new FileOutputStream(buf), "Support Request");
} finally {
out.close();
}
} catch (Throwable ex) {
ex.printStackTrace();
}
return tmp;
}
/**
* Opens a new <code>ZipFile</code> to read from the specified
* <code>File</code> object in the specified mode. The mode argument
* must be either <tt>OPEN_READ</tt> or <tt>OPEN_READ | OPEN_DELETE</tt>.
*
* <p>First, if there is a security manager, its <code>checkRead</code>
* method is called with the <code>name</code> argument as its argument to
* ensure the read is allowed.
*
* @param file the ZIP file to be opened for reading
* @param mode the mode in which the file is to be opened
* @param charset
* the {@linkplain java.nio.charset.Charset charset} to
* be used to decode the ZIP entry name and comment that are not
* encoded by using UTF-8 encoding (indicated by entry's general
* purpose flag).
*
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
*
* @throws SecurityException
* if a security manager exists and its <code>checkRead</code>
* method doesn't allow read access to the file,or its
* <code>checkDelete</code> method doesn't allow deleting the
* file when the <tt>OPEN_DELETE</tt> flag is set
*
* @throws IllegalArgumentException if the <tt>mode</tt> argument is invalid
*
* @see SecurityManager#checkRead(java.lang.String)
*
* @since 1.7
*/
public ZipFile(File file, int mode, Charset charset) throws IOException
{
if (((mode & OPEN_READ) == 0) ||
((mode & ~(OPEN_READ | OPEN_DELETE)) != 0)) {
throw new IllegalArgumentException("Illegal mode: 0x"+
Integer.toHexString(mode));
}
String name = file.getPath();
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkRead(name);
if ((mode & OPEN_DELETE) != 0) {
sm.checkDelete(name);
}
}
if (charset == null)
throw new NullPointerException("charset is null");
this.zc = ZipCoder.get(charset);
long t0 = System.nanoTime();
jzfile = open(name, mode, file.lastModified(), usemmap);
sun.misc.PerfCounter.getZipFileOpenTime().addElapsedTimeFrom(t0);
sun.misc.PerfCounter.getZipFileCount().increment();
this.name = name;
this.total = getTotal(jzfile);
this.locsig = startsWithLOC(jzfile);
}