JAVA PATH

原文地址:<http://www.fqf.cn/detail/427/9254272063354.html>

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

常用:

字符串类型:system.getproperty(&quot;user.dir&quot;);

综合:

package com.zcjl.test.base;
import java.io.file;
public class test {
    public static void main(string&#91;&#93; args) throws exception {
        system.out.println(
            thread.currentthread().getcontextclassloader().getresource(&quot;&quot;));
        system.out.println(test.class.getclassloader().getresource(&quot;&quot;));
        system.out.println(classloader.getsystemresource(&quot;&quot;));
        system.out.println(test.class.getresource(&quot;&quot;));
        system.out.println(test.class.getresource(&quot;/&quot;));
        system.out.println(new file(&quot;&quot;).getabsolutepath());
        system.out.println(system.getproperty(&quot;user.dir&quot;));
    }
}


2. web服务中

(1). weblogic

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

(2). tomcat

在类中输出system.getproperty(&quot;user.dir&quot;);显示的是% tomcat_home%/bin

(3). resin

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

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

java文件中getresource或getresourceasstream均可

例:getclass().getresourceasstream(filepath);//filepath可以是&quot;/filename&quot;,这里的/代表 web发布根路径下 web-inf/classes

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

string  file_real_path=request.getrealpath(&quot;mypath/filename&quot;);  

通常使用request.getrealpath(&quot;/&quot;);  

3.文件操作的类

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

/**
* 此类中封装一些常用的文件操作。
* 所有方法都是静态方法,不需要生成此类的实例,
* 为避免生成此类的实例,构造方法被申明为private类型的。
* @since  0.1
*/

public class fileutil {
  /**
   * 私有构造方法,防止类的实例化,因为工具类不需要实例化。
   */
  private fileutil() {

  }

  /**
   * 修改文件的最后访问时间。
   * 如果文件不存在则创建该文件。
   * <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考

虑中。</b>
   * @param file 需要修改最后访问时间的文件。
   * @since  0.1
   */
  public static void touch(file file) {
    long currenttime = system.currenttimemillis();
    if (!file.exists()) {
      system.err.println(&quot;file not found:&quot; + file.getname());
      system.err.println(&quot;create a new file:&quot; + file.getname());
      try {
        if (file.createnewfile()) {
        //  system.out.println(&quot;succeeded!&quot;);
        }
        else {
        //  system.err.println(&quot;create file failed!&quot;);
        }
      }
      catch (ioexception e) {
      //  system.err.println(&quot;create file failed!&quot;);
        e.printstacktrace();
      }
    }
    boolean result = file.setlastmodified(currenttime);
    if (!result) {
    //  system.err.println(&quot;touch failed: &quot; + file.getname());
    }
  }

  /**
   * 修改文件的最后访问时间。
   * 如果文件不存在则创建该文件。
   * <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考

虑中。</b>
   * @param filename 需要修改最后访问时间的文件的文件名。
   * @since  0.1
   */
  public static void touch(string filename) {
    file file = new file(filename);
    touch(file);
  }

  /**
   * 修改文件的最后访问时间。
   * 如果文件不存在则创建该文件。
   * <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考

虑中。</b>
   * @param files 需要修改最后访问时间的文件数组。
   * @since  0.1
   */
  public static void touch(file&#91;&#93; files) {
    for (int i = 0; i < files.length; i++) {
      touch(files);
    }
  }

  /**
   * 修改文件的最后访问时间。
   * 如果文件不存在则创建该文件。
   * <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考

虑中。</b>
   * @param filenames 需要修改最后访问时间的文件名数组。
   * @since  0.1
   */
  public static void touch(string&#91;&#93; filenames) {
    file&#91;&#93; files = new file&#91;filenames.length&#93;;
    for (int i = 0; i < filenames.length; i++) {
      files = new file(filenames);
    }
    touch(files);
  }

  /**
   * 判断指定的文件是否存在。
   * @param filename 要判断的文件的文件名
   * @return 存在时返回true,否则返回false。
   * @since  0.1
   */
  public static boolean isfileexist(string filename) {
    return new file(filename).isfile();
  }

  /**
   * 创建指定的目录。
   * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。
   * <b>注意:可能会在返回false的时候创建部分父目录。</b>
   * @param file 要创建的目录
   * @return 完全创建成功时返回true,否则返回false。
   * @since  0.1
   */
  public static boolean makedirectory(file file) {
    file parent = file.getparentfile();
    if (parent != null) {
      return parent.mkdirs();
    }
    return false;
  }

  /**
   * 创建指定的目录。
   * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。
   * <b>注意:可能会在返回false的时候创建部分父目录。</b>
   * @param filename 要创建的目录的目录名
   * @return 完全创建成功时返回true,否则返回false。
   * @since  0.1
   */
  public static boolean makedirectory(string filename) {
    file file = new file(filename);
    return makedirectory(file);
  }

  /**
   * 清空指定目录中的文件。
   * 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。
   * 另外这个方法不会迭代删除,即不会删除子目录及其内容。
   * @param directory 要清空的目录
   * @return 目录下的所有文件都被成功删除时返回true,否则返回false.
   * @since  0.1
   */
  public static boolean emptydirectory(file directory) {
    boolean result = false;
    file&#91;&#93; entries = directory.listfiles();
    for (int i = 0; i < entries.length; i++) {
      if (!entries.delete()) {
        result = false;
      }
    }
    return true;
  }

  /**
   * 清空指定目录中的文件。
   * 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。
   * 另外这个方法不会迭代删除,即不会删除子目录及其内容。
   * @param directoryname 要清空的目录的目录名
   * @return 目录下的所有文件都被成功删除时返回true,否则返回false。
   * @since  0.1
   */
  public static boolean emptydirectory(string directoryname) {
    file dir = new file(directoryname);
    return emptydirectory(dir);
  }

  /**
   * 删除指定目录及其中的所有内容。
   * @param dirname 要删除的目录的目录名
   * @return 删除成功时返回true,否则返回false。
   * @since  0.1
   */
  public static boolean deletedirectory(string dirname) {
    return deletedirectory(new file(dirname));
  }

  /**
   * 删除指定目录及其中的所有内容。
   * @param dir 要删除的目录
   * @return 删除成功时返回true,否则返回false。
   * @since  0.1
   */
  public static boolean deletedirectory(file dir) {
    if ( (dir == null) !dir.isdirectory()) {
      throw new illegalargumentexception(&quot;argument &quot; + dir +
                                         &quot; is not a directory. &quot;);
    }

    file&#91;&#93; 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;
  }




  /**
   * 返回文件的url地址。
   * @param file 文件
   * @return 文件对应的的url地址
   * @throws malformedurlexception
   * @since  0.4
   * @deprecated 在实现的时候没有注意到file类本身带一个tourl方法将文件路径转换为url。
   *             请使用file.tourl方法。
   */
  public static url geturl(file file) throws malformedurlexception {
    string fileurl = &quot;file:/&quot; + file.getabsolutepath();
    url url = new url(fileurl);
    return url;
  }

  /**
   * 从文件路径得到文件名。
   * @param filepath 文件的路径,可以是相对路径也可以是绝对路径
   * @return 对应的文件名
   * @since  0.4
   */
  public static string getfilename(string filepath) {
    file file = new file(filepath);
    return file.getname();
  }

  /**
   * 从文件名得到文件绝对路径。
   * @param filename 文件名
   * @return 对应的文件路径
   * @since  0.4
   */
  public static string getfilepath(string filename) {
    file file = new file(filename);
    return file.getabsolutepath();
  }

  /**
   * 将dos/windows格式的路径转换为unix/linux格式的路径。
   * 其实就是将路径中的&quot;/&quot;全部换为&quot;/&quot;,因为在某些情况下我们转换为这种方式比较方便,
   * 某中程度上说&quot;/&quot;比&quot;/&quot;更适合作为路径分隔符,而且dos/windows也将它当作路径分隔符。
   * @param filepath 转换前的路径
   * @return 转换后的路径
   * @since  0.4
   */
  public static string tounixpath(string filepath) {
    return filepath.replace('//', '/');
  }

  /**
   * 从文件名得到unix风格的文件绝对路径。
   * @param filename 文件名
   * @return 对应的unix风格的文件路径
   * @since  0.4
   * @see #tounixpath(string filepath) tounixpath
   */
  public static string getunixfilepath(string filename) {
    file file = new file(filename);
    return tounixpath(file.getabsolutepath());
  }

  /**
   * 得到文件的类型。
   * 实际上就是得到文件名中最后一个&ldquo;.&rdquo;后面的部分。
   * @param filename 文件名
   * @return 文件名中的类型部分
   * @since  0.5
   */
  public static string gettypepart(string filename) {
    int point = filename.lastindexof('.');
    int length = filename.length();
    if (point == -1 point == length - 1) {
      return &quot;&quot;;
    }
    else {
      return filename.substring(point + 1, length);
    }
  }

  /**
   * 得到文件的类型。
   * 实际上就是得到文件名中最后一个&ldquo;.&rdquo;后面的部分。
   * @param file 文件
   * @return 文件名中的类型部分
   * @since  0.5
   */
  public static string getfiletype(file file) {
    return gettypepart(file.getname());
  }

  /**
   * 得到文件的名字部分。
   * 实际上就是路径中的最后一个路径分隔符后的部分。
   * @param filename 文件名
   * @return 文件名中的名字部分
   * @since  0.5
   */
  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);
    }
  }

  /**
   * 得到文件名中的父路径部分。
   * 对两种路径分隔符都有效。
   * 不存在时返回&quot;&quot;。
   * 如果文件名是以路径分隔符结尾的则不考虑该分隔符,例如&quot;/path/&quot;返回&quot;&quot;。
   * @param filename 文件名
   * @return 父路径,不存在或者已经是父目录时返回&quot;&quot;
   * @since  0.5
   */
  public static string getpathpart(string filename) {
    int point = getpathlsatindex(filename);
    int length = filename.length();
    if (point == -1) {
      return &quot;&quot;;
    }
    else if (point == length - 1) {
      int secondpoint = getpathlsatindex(filename, point - 1);
      if (secondpoint == -1) {
        return &quot;&quot;;
      }
      else {
        return filename.substring(0, secondpoint);
      }
    }
    else {
      return filename.substring(0, point);
    }
  }

  /**
   * 得到路径分隔符在文件路径中首次出现的位置。
   * 对于dos或者unix风格的分隔符都可以。
   * @param filename 文件路径
   * @return 路径分隔符在路径中首次出现的位置,没有出现时返回-1。
   * @since  0.5
   */
  public static int getpathindex(string filename) {
    int point = filename.indexof('/');
    if (point == -1) {
      point = filename.indexof('//');
    }
    return point;
  }

  /**
   * 得到路径分隔符在文件路径中指定位置后首次出现的位置。
   * 对于dos或者unix风格的分隔符都可以。
   * @param filename 文件路径
   * @param fromindex 开始查找的位置
   * @return 路径分隔符在路径中指定位置后首次出现的位置,没有出现时返回-1。
   * @since  0.5
   */
  public static int getpathindex(string filename, int fromindex) {
    int point = filename.indexof('/', fromindex);
    if (point == -1) {
      point = filename.indexof('//', fromindex);
    }
    return point;
  }

  /**
   * 得到路径分隔符在文件路径中最后出现的位置。
   * 对于dos或者unix风格的分隔符都可以。
   * @param filename 文件路径
   * @return 路径分隔符在路径中最后出现的位置,没有出现时返回-1。
   * @since  0.5
   */
  public static int getpathlsatindex(string filename) {
    int point = filename.lastindexof('/');
    if (point == -1) {
      point = filename.lastindexof('//');
    }
    return point;
  }

  /**
   * 得到路径分隔符在文件路径中指定位置前最后出现的位置。
   * 对于dos或者unix风格的分隔符都可以。
   * @param filename 文件路径
   * @param fromindex 开始查找的位置
   * @return 路径分隔符在路径中指定位置前最后出现的位置,没有出现时返回-1。
   * @since  0.5
   */
  public static int getpathlsatindex(string filename, int fromindex) {
    int point = filename.lastindexof('/', fromindex);
    if (point == -1) {
      point = filename.lastindexof('//', fromindex);
    }
    return point;
  }

  /**
   * 将文件名中的类型部分去掉。
   * @param filename 文件名
   * @return 去掉类型部分的结果
   * @since  0.5
   */
  public static string trimtype(string filename) {
    int index = filename.lastindexof(&quot;.&quot;);
    if (index != -1) {
      return filename.substring(0, index);
    }
    else {
      return filename;
    }
  }
  /**
   * 得到相对路径。
   * 文件名不是目录名的子节点时返回文件名。
   * @param pathname 目录名
   * @param filename 文件名
   * @return 得到文件名相对于目录名的相对路径,目录下不存在该文件时返回文件名
   * @since  0.5
   */
  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(&quot;xx.properties&quot;)获取;application可以通过new fileinputstream(&quot;xx.properties&quot;);直接在classes一级获取。关键是有时我们需要通过 web修改配置文件,我们不能将路径写死了。经过 测试觉得有以下心得:

1. servlet中读写。如果运用 struts或者 servlet可以直接在初始化参数中配置,调用时根据 servlet的getrealpath(&quot;/&quot;)获取真实路径,再根据string file = this. servlet.getinitparameter(&quot;abc&quot;);获取相对的 web-inf的相对路径。
例:
inputstream input = thread.currentthread().getcontextclassloader().
getresourceasstream(&quot;abc.properties&quot;);
properties prop = new properties();
prop.load(input);
input.close();
outputstream out = new fileoutputstream(path);
prop.setproperty(&quot;abc&quot;, &ldquo;test&quot;);
prop.store(out, &ldquo;&ndash;test&ndash;&quot;);
out.close();


2.直接在 jsp中操作,通过 jsp内置对象获取可操作的绝对地址。
例:
// jsp页面
string path = pagecontext.getservletcontext().getrealpath(&quot;/&quot;);
string realpath = path+&quot;/web-inf/classes/abc.properties&quot;;

//java 程序
inputstream in = getclass().getclassloader().getresourceasstream(&quot;abc.properties&quot;); // abc.properties放在webroot/web-inf/classes/目录下
prop.load(in);
in.close();

outputstream out = new fileoutputstream(path); // path为通过页面传入的路径
prop.setproperty(&quot;abc&quot;, &ldquo;abcccccc&quot;);
prop.store(out, &ldquo;&ndash;test&ndash;&quot;);
out.close();


3.只通过 java程序操作资源文件
inputstream in = new fileinputstream(&quot;abc.properties&quot;); // 放在classes同级

outputstream out = new fileoutputstream(&quot;abc.properties&quot;); 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值