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() {
}
/**
* 修改文件的最后访问时间。
* 如果文件不存在则创建该文件。
*
目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考
虑中。 * @param file 需
要修改最后访问时间的文件。
* @since 0.1
*/
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());
}
}
/**
* 修改文件的最后访问时间。
* 如果文件不存在则创建该文件。
*
目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考
虑中。 *