选择显示字体大小

关于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.*;

/**
* 此类中封装一些常用的文件操作。
* 所有方法都是静态方法,不需要生成此类的实例,
* 为避免生成此类的实例,构造方法被申明为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;);



 


关键字 本文所属关键字

相关 与本文相关文章

分类 所有文章关键字导航

源码编程相关

Java   Asp   PHP   .Net   XML   C/C++   CGI   VB   Jsp   J2ee   J2se   J2me   EJB   Servlet   Tomcat   Resin   Struts   Weblogic   Eclipse   ANT   GUI   JMS   Web servise   IDEA   Webphere   Hibernate   Spring   Jboss   Applet   Swing   Socket   Javamail   Perl   Ajax   P2P   安全   模式   框架   测试   开源   游戏

SQL数据库相关

My-SQL   Ms-SQL   Access   DB2   Oracle   Sybase   SQLserver   索引   存储过程   加密   数据库   分页   视图  

手机无线相关

3G   Wap   CDMA   GRPS   GSM   IVR   彩信   短信   无线   增值业务

网页设计制作相关

HTML   CSS   网页配色   网页特效   Javascript   VBscript   Dreamweaver   Frontpage   JS   Web   网站设计

网站建设推广相关

建站经验   网站优化   网站排名   推广   Alexa

操作系统/服务器相关

Windows XP   Windows 2000   Windows 2003   Windows Me   Windows 9.x   Linux   UNIX   注册表   操作系统   服务器   应用服务器

图形图像多媒体相关

Photoshop   Fireworks   Flash   Coreldraw   Illustrator   Freehand   Photoimpact   多媒体   图形图像

标准 网站致力的规范

Valid CSS!

无不良内容,无不良广告,无恶意代码

Valid XHTML 1.0 Transitional

creativecommons