关于Java文件路径问题

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

常用:

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

综合:

  1. package com.zcjl.test.base;
  2. import java.io.File;
  3. public class Test {
  4.     public static void main(String[] args) throws Exception {
  5.         System.out.println(
  6.             Thread.currentThread().getContextClassLoader().getResource(""));
  7.         System.out.println(Test.class.getClassLoader().getResource(""));
  8.         System.out.println(ClassLoader.getSystemResource(""));
  9.         System.out.println(Test.class.getResource(""));
  10.         System.out.println(Test.class.getResource("/"));
  11.         System.out.println(new File("").getAbsolutePath());
  12.         System.out.println(System.getProperty("user.dir"));
  13.     }
  14. }

 

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.文件操作的类

  1. import java.io.*;
  2. import java.net.*;
  3. import java.util.*;
  4. //import javax.swing.filechooser.*;
  5. //import org.jr.swing.filter.*;
  6. /**
  7.  * 此类中封装一些常用的文件操作。 所有方法都是静态方法,不需要生成此类的实例, 为避免生成此类的实例,构造方法被申明为private类型的。
  8.  * 
  9.  * @since 0.1
  10.  */
  11. public class FileUtil {
  12.     /**
  13.      * 私有构造方法,防止类的实例化,因为工具类不需要实例化。
  14.      */
  15.     private FileUtil() {
  16.     }
  17.     /**
  18.      * 修改文件的最后访问时间。 如果文件不存在则创建该文件。 <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考
  19.      * 
  20.      * 虑中。</b>
  21.      * 
  22.      * @param file
  23.      *            需要修改最后访问时间的文件。
  24.      * @since 0.1
  25.      */
  26.     public static void touch(File file) {
  27.         long currentTime = System.currentTimeMillis();
  28.         if (!file.exists()) {
  29.             System.err.println("file not found:" + file.getName());
  30.             System.err.println("Create a new file:" + file.getName());
  31.             try {
  32.                 if (file.createNewFile()) {
  33.                     // System.out.println("Succeeded!");
  34.                 } else {
  35.                     // System.err.println("Create file failed!");
  36.                 }
  37.             } catch (IOException e) {
  38.                 // System.err.println("Create file failed!");
  39.                 e.printStackTrace();
  40.             }
  41.         }
  42.         boolean result = file.setLastModified(currentTime);
  43.         if (!result) {
  44.             // System.err.println("touch failed: " + file.getName());
  45.         }
  46.     }
  47.     /**
  48.      * 修改文件的最后访问时间。 如果文件不存在则创建该文件。 <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考
  49.      * 
  50.      * 虑中。</b>
  51.      * 
  52.      * @param fileName
  53.      *            需要修改最后访问时间的文件的文件名。
  54.      * @since 0.1
  55.      */
  56.     public static void touch(String fileName) {
  57.         File file = new File(fileName);
  58.         touch(file);
  59.     }
  60.     /**
  61.      * 修改文件的最后访问时间。 如果文件不存在则创建该文件。 <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考
  62.      * 
  63.      * 虑中。</b>
  64.      * 
  65.      * @param files
  66.      *            需要修改最后访问时间的文件数组。
  67.      * @since 0.1
  68.      */
  69.     public static void touch(File[] files) {
  70.         for (int i = 0; i < files.length; i++) {
  71.             touch(files);
  72.         }
  73.     }
  74.     /**
  75.      * 修改文件的最后访问时间。 如果文件不存在则创建该文件。 <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考
  76.      * 
  77.      * 虑中。</b>
  78.      * 
  79.      * @param fileNames
  80.      *            需要修改最后访问时间的文件名数组。
  81.      * @since 0.1
  82.      */
  83.     public static void touch(String[] fileNames) {
  84.         File[] files = new File[fileNames.length];
  85.         for (int i = 0; i < fileNames.length; i++) {
  86.             files[i] = new File(fileNames[i]);
  87.         }
  88.         touch(files);
  89.     }
  90.     /**
  91.      * 判断指定的文件是否存在。
  92.      * 
  93.      * @param fileName
  94.      *            要判断的文件的文件名
  95.      * @return 存在时返回true,否则返回false。
  96.      * @since 0.1
  97.      */
  98.     public static boolean isFileExist(String fileName) {
  99.         return new File(fileName).isFile();
  100.     }
  101.     /**
  102.      * 创建指定的目录。 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。 <b>注意:可能会在返回false的时候创建部分父目录。</b>
  103.      * 
  104.      * @param file
  105.      *            要创建的目录
  106.      * @return 完全创建成功时返回true,否则返回false。
  107.      * @since 0.1
  108.      */
  109.     public static boolean makeDirectory(File file) {
  110.         File parent = file.getParentFile();
  111.         if (parent != null) {
  112.             return parent.mkdirs();
  113.         }
  114.         return false;
  115.     }
  116.     /**
  117.      * 创建指定的目录。 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。 <b>注意:可能会在返回false的时候创建部分父目录。</b>
  118.      * 
  119.      * @param fileName
  120.      *            要创建的目录的目录名
  121.      * @return 完全创建成功时返回true,否则返回false。
  122.      * @since 0.1
  123.      */
  124.     public static boolean makeDirectory(String fileName) {
  125.         File file = new File(fileName);
  126.         return makeDirectory(file);
  127.     }
  128.     /**
  129.      * 清空指定目录中的文件。 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。
  130.      * 另外这个方法不会迭代删除,即不会删除子目录及其内容。
  131.      * 
  132.      * @param directory
  133.      *            要清空的目录
  134.      * @return 目录下的所有文件都被成功删除时返回true,否则返回false.
  135.      * @since 0.1
  136.      */
  137.     public static boolean emptyDirectory(File directory) {
  138.         boolean result = false;
  139.         File[] entries = directory.listFiles();
  140.         for (int i = 0; i < entries.length; i++) {
  141.             if (!entries[i].delete()) {
  142.                 result = false;
  143.             }
  144.         }
  145.         return true;
  146.     }
  147.     /**
  148.      * 清空指定目录中的文件。 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。
  149.      * 另外这个方法不会迭代删除,即不会删除子目录及其内容。
  150.      * 
  151.      * @param directoryName
  152.      *            要清空的目录的目录名
  153.      * @return 目录下的所有文件都被成功删除时返回true,否则返回false。
  154.      * @since 0.1
  155.      */
  156.     public static boolean emptyDirectory(String directoryName) {
  157.         File dir = new File(directoryName);
  158.         return emptyDirectory(dir);
  159.     }
  160.     /**
  161.      * 删除指定目录及其中的所有内容。
  162.      * 
  163.      * @param dirName
  164.      *            要删除的目录的目录名
  165.      * @return 删除成功时返回true,否则返回false。
  166.      * @since 0.1
  167.      */
  168.     public static boolean deleteDirectory(String dirName) {
  169.         return deleteDirectory(new File(dirName));
  170.     }
  171.     /**
  172.      * 删除指定目录及其中的所有内容。
  173.      * 
  174.      * @param dir
  175.      *            要删除的目录
  176.      * @return 删除成功时返回true,否则返回false。
  177.      * @since 0.1
  178.      */
  179.     public static boolean deleteDirectory(File dir) {
  180.         if ((dir == null) || !dir.isDirectory()) {
  181.             throw new IllegalArgumentException("Argument " + dir
  182.                     + " is not a directory. ");
  183.         }
  184.         File[] entries = dir.listFiles();
  185.         int sz = entries.length;
  186.         for (int i = 0; i < sz; i++) {
  187.             if (entries[i].isDirectory()) {
  188.                 if (!deleteDirectory(entries[i])) {
  189.                     return false;
  190.                 }
  191.             } else {
  192.                 if (!entries[i].delete()) {
  193.                     return false;
  194.                 }
  195.             }
  196.         }
  197.         if (!dir.delete()) {
  198.             return false;
  199.         }
  200.         return true;
  201.     }
  202.     /**
  203.      * 返回文件的URL地址。
  204.      * 
  205.      * @param file
  206.      *            文件
  207.      * @return 文件对应的的URL地址
  208.      * @throws MalformedURLException
  209.      * @since 0.4
  210.      * @deprecated 在实现的时候没有注意到File类本身带一个toURL方法将文件路径转换为URL。 请使用File.toURL方法。
  211.      */
  212.     public static URL getURL(File file) throws MalformedURLException {
  213.         String fileURL = "file:/" + file.getAbsolutePath();
  214.         URL url = new URL(fileURL);
  215.         return url;
  216.     }
  217.     /**
  218.      * 从文件路径得到文件名。
  219.      * 
  220.      * @param filePath
  221.      *            文件的路径,可以是相对路径也可以是绝对路径
  222.      * @return 对应的文件名
  223.      * @since 0.4
  224.      */
  225.     public static String getFileName(String filePath) {
  226.         File file = new File(filePath);
  227.         return file.getName();
  228.     }
  229.     /**
  230.      * 从文件名得到文件绝对路径。
  231.      * 
  232.      * @param fileName
  233.      *            文件名
  234.      * @return 对应的文件路径
  235.      * @since 0.4
  236.      */
  237.     public static String getFilePath(String fileName) {
  238.         File file = new File(fileName);
  239.         return file.getAbsolutePath();
  240.     }
  241.     /**
  242.      * 将DOS/Windows格式的路径转换为UNIX/Linux格式的路径。
  243.      * 其实就是将路径中的"/"全部换为"/",因为在某些情况下我们转换为这种方式比较方便,
  244.      * 某中程度上说"/"比"/"更适合作为路径分隔符,而且DOS/Windows也将它当作路径分隔符。
  245.      * 
  246.      * @param filePath
  247.      *            转换前的路径
  248.      * @return 转换后的路径
  249.      * @since 0.4
  250.      */
  251.     public static String toUNIXpath(String filePath) {
  252.         return filePath.replace('//', '/');
  253.     }
  254.     /**
  255.      * 从文件名得到UNIX风格的文件绝对路径。
  256.      * 
  257.      * @param fileName
  258.      *            文件名
  259.      * @return 对应的UNIX风格的文件路径
  260.      * @since 0.4
  261.      * @see #toUNIXpath(String filePath) toUNIXpath
  262.      */
  263.     public static String getUNIXfilePath(String fileName) {
  264.         File file = new File(fileName);
  265.         return toUNIXpath(file.getAbsolutePath());
  266.     }
  267.     /**
  268.      * 得到文件的类型。 实际上就是得到文件名中最后一个“.”后面的部分。
  269.      * 
  270.      * @param fileName
  271.      *            文件名
  272.      * @return 文件名中的类型部分
  273.      * @since 0.5
  274.      */
  275.     public static String getTypePart(String fileName) {
  276.         int point = fileName.lastIndexOf('.');
  277.         int length = fileName.length();
  278.         if (point == -1 || point == length - 1) {
  279.             return "";
  280.         } else {
  281.             return fileName.substring(point + 1, length);
  282.         }
  283.     }
  284.     /**
  285.      * 得到文件的类型。 实际上就是得到文件名中最后一个“.”后面的部分。
  286.      * 
  287.      * @param file
  288.      *            文件
  289.      * @return 文件名中的类型部分
  290.      * @since 0.5
  291.      */
  292.     public static String getFileType(File file) {
  293.         return getTypePart(file.getName());
  294.     }
  295.     /**
  296.      * 得到文件的名字部分。 实际上就是路径中的最后一个路径分隔符后的部分。
  297.      * 
  298.      * @param fileName
  299.      *            文件名
  300.      * @return 文件名中的名字部分
  301.      * @since 0.5
  302.      */
  303.     public static String getNamePart(String fileName) {
  304.         int point = getPathLsatIndex(fileName);
  305.         int length = fileName.length();
  306.         if (point == -1) {
  307.             return fileName;
  308.         } else if (point == length - 1) {
  309.             int secondPoint = getPathLsatIndex(fileName, point - 1);
  310.             if (secondPoint == -1) {
  311.                 if (length == 1) {
  312.                     return fileName;
  313.                 } else {
  314.                     return fileName.substring(0, point);
  315.                 }
  316.             } else {
  317.                 return fileName.substring(secondPoint + 1, point);
  318.             }
  319.         } else {
  320.             return fileName.substring(point + 1);
  321.         }
  322.     }
  323.     /**
  324.      * 得到文件名中的父路径部分。 对两种路径分隔符都有效。 不存在时返回""。
  325.      * 如果文件名是以路径分隔符结尾的则不考虑该分隔符,例如"/path/"返回""。
  326.      * 
  327.      * @param fileName
  328.      *            文件名
  329.      * @return 父路径,不存在或者已经是父目录时返回""
  330.      * @since 0.5
  331.      */
  332.     public static String getPathPart(String fileName) {
  333.         int point = getPathLsatIndex(fileName);
  334.         int length = fileName.length();
  335.         if (point == -1) {
  336.             return "";
  337.         } else if (point == length - 1) {
  338.             int secondPoint = getPathLsatIndex(fileName, point - 1);
  339.             if (secondPoint == -1) {
  340.                 return "";
  341.             } else {
  342.                 return fileName.substring(0, secondPoint);
  343.             }
  344.         } else {
  345.             return fileName.substring(0, point);
  346.         }
  347.     }
  348.     /**
  349.      * 得到路径分隔符在文件路径中首次出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
  350.      * 
  351.      * @param fileName
  352.      *            文件路径
  353.      * @return 路径分隔符在路径中首次出现的位置,没有出现时返回-1。
  354.      * @since 0.5
  355.      */
  356.     public static int getPathIndex(String fileName) {
  357.         int point = fileName.indexOf('/');
  358.         if (point == -1) {
  359.             point = fileName.indexOf('//');
  360.         }
  361.         return point;
  362.     }
  363.     /**
  364.      * 得到路径分隔符在文件路径中指定位置后首次出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
  365.      * 
  366.      * @param fileName
  367.      *            文件路径
  368.      * @param fromIndex
  369.      *            开始查找的位置
  370.      * @return 路径分隔符在路径中指定位置后首次出现的位置,没有出现时返回-1。
  371.      * @since 0.5
  372.      */
  373.     public static int getPathIndex(String fileName, int fromIndex) {
  374.         int point = fileName.indexOf('/', fromIndex);
  375.         if (point == -1) {
  376.             point = fileName.indexOf('//', fromIndex);
  377.         }
  378.         return point;
  379.     }
  380.     /**
  381.      * 得到路径分隔符在文件路径中最后出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
  382.      * 
  383.      * @param fileName
  384.      *            文件路径
  385.      * @return 路径分隔符在路径中最后出现的位置,没有出现时返回-1。
  386.      * @since 0.5
  387.      */
  388.     public static int getPathLsatIndex(String fileName) {
  389.         int point = fileName.lastIndexOf('/');
  390.         if (point == -1) {
  391.             point = fileName.lastIndexOf('//');
  392.         }
  393.         return point;
  394.     }
  395.     /**
  396.      * 得到路径分隔符在文件路径中指定位置前最后出现的位置。 对于DOS或者UNIX风格的分隔符都可以。
  397.      * 
  398.      * @param fileName
  399.      *            文件路径
  400.      * @param fromIndex
  401.      *            开始查找的位置
  402.      * @return 路径分隔符在路径中指定位置前最后出现的位置,没有出现时返回-1。
  403.      * @since 0.5
  404.      */
  405.     public static int getPathLsatIndex(String fileName, int fromIndex) {
  406.         int point = fileName.lastIndexOf('/', fromIndex);
  407.         if (point == -1) {
  408.             point = fileName.lastIndexOf('//', fromIndex);
  409.         }
  410.         return point;
  411.     }
  412.     /**
  413.      * 将文件名中的类型部分去掉。
  414.      * 
  415.      * @param filename
  416.      *            文件名
  417.      * @return 去掉类型部分的结果
  418.      * @since 0.5
  419.      */
  420.     public static String trimType(String filename) {
  421.         int index = filename.lastIndexOf(".");
  422.         if (index != -1) {
  423.             return filename.substring(0, index);
  424.         } else {
  425.             return filename;
  426.         }
  427.     }
  428.     /**
  429.      * 得到相对路径。 文件名不是目录名的子节点时返回文件名。
  430.      * 
  431.      * @param pathName
  432.      *            目录名
  433.      * @param fileName
  434.      *            文件名
  435.      * @return 得到文件名相对于目录名的相对路径,目录下不存在该文件时返回文件名
  436.      * @since 0.5
  437.      */
  438.     public static String getSubpath(String pathName, String fileName) {
  439.         int index = fileName.indexOf(pathName);
  440.         if (index != -1) {
  441.             return fileName.substring(index + pathName.length() + 1);
  442.         } else {
  443.             return fileName;
  444.         }
  445.     }
  446. }

 

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");

 

原文引自:http://java998.javaeye.com/blog/66474

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值