获取Java文件路径

标签: 

if

 

文件路径

 

dir

 

父目录

 

分隔符

 

杂谈

分类: java

1.如何获得当前文件路径

常用:

字符串类型:System.getProperty("user.dir");

综合:

package com.zcjl.test.base;
import java.io.File;
public class Test {
public static void main(String[] args) throws Exception {
System.out.println(
Thread.currentThread().getContextClassLoader().getResource(""));
System.out.println(Test.class.getClassLoader().getResource(""));
System.out.println(ClassLoader.getSystemResource(""));
System.out.println(Test.class.getResource(""));
System.out.println(Test.class.getResource("/"));
System.out.println(new File("").getAbsolutePath());
System.out.println(System.getProperty("user.dir"));
}
}

2.Web服务中

(1).Weblogic

WebApplication的系统文件根目录是你的weblogic安装所在根目录。
例如:如果你的weblogic安装在c:\bea\weblogic700.....
那么,你的文件根路径就是c:\.
所以,有两种方式能够让你访问你的服务器端的文件:
a.使用绝对路径:
比如将你的参数文件放在c:\yourconfig\yourconf.properties,
直接使用 new FileInputStream("yourconfig/yourconf.properties");
b.使用相对路径:
相对路径的根目录就是你的webapplication的根路径,即WEB-INF的上一级目录,将你的参数文件放在yourwebapp\yourconfig\yourconf.properties,
这样使用:
new FileInputStream("./yourconfig/yourconf.properties");
这两种方式均可,自己选择。

(2).Tomcat

在类中输出System.getProperty("user.dir");显示的是%Tomcat_Home%/bin

(3).Resin

不是你的JSP放的相对路径,是JSP引擎执行这个JSP编译成SERVLET
的路径为根.比如用新建文件法测试File f = new File("a.htm");
这个a.htm在resin的安装目录下

(4).如何读相对路径哪?

在Java文件中getResource或getResourceAsStream均可

例:getClass().getResourceAsStream(filePath);//filePath可以是"/filename",这里的/代表web发布根路径下WEB-INF/classes

(5).获得文件真实路径

string file_real_path=request.getRealPath("mypath/filename");

通常使用request.getRealPath("/");

3.文件操作的类

import java.io.*;
import java.net.*;
import java.util.*;
//import javax.swing.filechooser.*;
//import org.jr.swing.filter.*;

 

public class FileUtil {

private FileUtil() {

}


public static void touch(File file) {
long currentTime = System.currentTimeMillis();
if (!file.exists()) {
System.err.println("file not found:" file.getName());
System.err.println("Create a new file:" file.getName());
try {
if (file.createNewFile()) {
// System.out.println("Succeeded!");
}
else {
// System.err.println("Create file failed!");
}
}
catch (IOException e) {
// System.err.println("Create file failed!");
e.printStackTrace();
}
}
boolean result = file.setLastModified(currentTime);
if (!result) {
// System.err.println("touch failed: " file.getName());
}
}


public static void touch(String fileName) {
File file = new File(fileName);
touch(file);
}


public static void touch(File[] files) {
for (int i = 0; i < files.length; i ) {
touch(files);
}
}


public static void touch(String[] fileNames) {
File[] files = new File[fileNames.length];
for (int i = 0; i < fileNames.length; i ) {
files = new File(fileNames);
}
touch(files);
}


public static boolean isFileExist(String fileName) {
return new File(fileName).isFile();
}


public static boolean makeDirectory(File file) {
File parent = file.getParentFile();
if (parent != null) {
return parent.mkdirs();
}
return false;
}


public static boolean makeDirectory(String fileName) {
File file = new File(fileName);
return makeDirectory(file);
}


public static boolean emptyDirectory(File directory) {
boolean result = false;
File[] entries = directory.listFiles();
for (int i = 0; i < entries.length; i ) {
if (!entries.delete()) {
result = false;
}
}
return true;
}


public static boolean emptyDirectory(String directoryName) {
File dir = new File(directoryName);
return emptyDirectory(dir);
}


public static boolean deleteDirectory(String dirName) {
return deleteDirectory(new File(dirName));
}


public static boolean deleteDirectory(File dir) {
if ( (dir == null) || !dir.isDirectory()) {
throw new IllegalArgumentException("Argument " dir
" is not a directory. ");
}

File[] entries = dir.listFiles();
int sz = entries.length;

for (int i = 0; i < sz; i ) {
if (entries.isDirectory()) {
if (!deleteDirectory(entries)) {
return false;
}
}
else {
if (!entries.delete()) {
return false;
}
}
}

if (!dir.delete()) {
return false;
}
return true;
}



public static URL getURL(File file) throws MalformedURLException {
String fileURL = "file:/" file.getAbsolutePath();
URL url = new URL(fileURL);
return url;
}


public static String getFileName(String filePath) {
File file = new File(filePath);
return file.getName();
}


public static String getFilePath(String fileName) {
File file = new File(fileName);
return file.getAbsolutePath();
}


public static String toUNIXpath(String filePath) {
return filePath.replace('\\', '/');
}


public static String getUNIXfilePath(String fileName) {
File file = new File(fileName);
return toUNIXpath(file.getAbsolutePath());
}


public static String getTypePart(String fileName) {
int point = fileName.lastIndexOf('.');
int length = fileName.length();
if (point == -1 || point == length - 1) {
return "";
}
else {
return fileName.substring(point 1, length);
}
}


public static String getFileType(File file) {
return getTypePart(file.getName());
}


public static String getNamePart(String fileName) {
int point = getPathLsatIndex(fileName);
int length = fileName.length();
if (point == -1) {
return fileName;
}
else if (point == length - 1) {
int secondPoint = getPathLsatIndex(fileName, point - 1);
if (secondPoint == -1) {
if (length == 1) {
return fileName;
}
else {
return fileName.substring(0, point);
}
}
else {
return fileName.substring(secondPoint 1, point);
}
}
else {
return fileName.substring(point 1);
}
}


public static String getPathPart(String fileName) {
int point = getPathLsatIndex(fileName);
int length = fileName.length();
if (point == -1) {
return "";
}
else if (point == length - 1) {
int secondPoint = getPathLsatIndex(fileName, point - 1);
if (secondPoint == -1) {
return "";
}
else {
return fileName.substring(0, secondPoint);
}
}
else {
return fileName.substring(0, point);
}
}


public static int getPathIndex(String fileName) {
int point = fileName.indexOf('/');
if (point == -1) {
point = fileName.indexOf('\\');
}
return point;
}


public static int getPathIndex(String fileName, int fromIndex) {
int point = fileName.indexOf('/', fromIndex);
if (point == -1) {
point = fileName.indexOf('\\', fromIndex);
}
return point;
}


public static int getPathLsatIndex(String fileName) {
int point = fileName.lastIndexOf('/');
if (point == -1) {
point = fileName.lastIndexOf('\\');
}
return point;
}


public static int getPathLsatIndex(String fileName, int fromIndex) {
int point = fileName.lastIndexOf('/', fromIndex);
if (point == -1) {
point = fileName.lastIndexOf('\\', fromIndex);
}
return point;
}


public static String trimType(String filename) {
int index = filename.lastIndexOf(".");
if (index != -1) {
return filename.substring(0, index);
}
else {
return filename;
}
}

public static String getSubpath(String pathName,String fileName) {
int index = fileName.indexOf(pathName);
if (index != -1) {
return fileName.substring(index pathName.length() 1);
}
else {
return fileName;
}
}

}
4.遗留问题

目前new FileInputStream()只会使用绝对路径,相对没用过,因为要相对于web服务器地址,比较麻烦

还不如写个配置文件来的快哪

5.按Java文件类型分类读取配置文件

配 置文件是应用系统中不可缺少的,可以增加程序的灵活性。java.util.Properties是从jdk1.2就有的类,一直到现在都支持load ()方法,jdk1.4以后save(output,string) ->store(output,string)。如果只是单纯的读,根本不存在烦恼的问题。web层可以通过 Thread.currentThread().getContextClassLoader().
getResourceAsStream("xx.properties") 获取;Application可以通过new FileInputStream("xx.properties");直接在classes一级获取。关键是有时我们需要通过web修改配置文件,我们不 能将路径写死了。经过测试觉得有以下心得:

1.servlet中读写。如果运用Struts 或者Servlet可以直接在初始化参数中配置,调用时根据servlet的getRealPath("/")获取真实路径,再根据String file = this.servlet.getInitParameter("abc");获取相对的WEB-INF的相对路径。
例:
InputStream input = Thread.currentThread().getContextClassLoader().
getResourceAsStream("abc.properties");
Properties prop = new Properties();
prop.load(input);
input.close();
OutputStream out = new FileOutputStream(path);
prop.setProperty("abc", “test");
prop.store(out, “–test–");
out.close();

2.直接在jsp中操作,通过jsp内置对象获取可操作的绝对地址。
例:
// jsp页面
String path = pageContext.getServletContext().getRealPath("/");
String realPath = path "/WEB-INF/classes/abc.properties";

//java 程序
InputStream in = getClass().getClassLoader().getResourceAsStream("abc.properties"); // abc.properties放在webroot/WEB-INF/classes/目录下
prop.load(in);
in.close();

OutputStream out = new FileOutputStream(path); // path为通过页面传入的路径
prop.setProperty("abc", “abcccccc");
prop.store(out, “–test–");
out.close();

3.只通过Java程序操作资源文件
InputStream in = new FileInputStream("abc.properties"); // 放在classes同级

OutputStream out = new FileOutputStream("abc.properties");

 


   public String getPathFromClass(Class cls) throws IOException {
     String path = null;
     if (cls == null) {
       throw new NullPointerException();
     }
     URL url = getClassLocationURL(cls);
     if (url != null) {
       path = url.getPath();
       if ("jar".equalsIgnoreCase(url.getProtocol())) {
         try {
           path = new URL(path).getPath();
         }
         catch (MalformedURLException e) {
         }
         int location = path.indexOf("!/");
         if (location != -1) {
           path = path.substring(0, location);
         }
       }
       File file = new File(path);
       path = file.getCanonicalPath();
     }
     return path;
   }

  
private URL getClassLocationURL(final Class cls) {
   if (cls == null) {
     throw new IllegalArgumentException("class that input is null");
   }
   URL result = null;
   final String clsAsResource = cls.getName().replace('.', '/').concat(".class");
   final ProtectionDomain pd = cls.getProtectionDomain();
   if (pd != null) {
     final CodeSource cs = pd.getCodeSource();
     if (cs != null) {
       result = cs.getLocation();

     }
     if (result != null) {
       if ("file".equals(result.getProtocol())) {
         try {
           if (result.toExternalForm().endsWith(".jar")
               || result.toExternalForm().endsWith(".zip")) {
             result = new URL("jar:".concat(
                 result.toExternalForm()).concat("!/")
                              .concat(clsAsResource));
           }
           else if (new File(result.getFile()).isDirectory()) {
             result = new URL(result, clsAsResource);
           }
         }
         catch (MalformedURLException ignore) {
         }
       }
     }
   }

   if (result == null) {
     final ClassLoader clsLoader = cls.getClassLoader();
     result = clsLoader != null ? clsLoader.getResource(clsAsResource)
         : ClassLoader.getSystemResource(clsAsResource);
   }
   return result;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值