java获取文件的路径怎么写

1. java获取某个文件夹的路径怎么写 File类有两个常用方法可以得到文件路径一个是:getCanonicalPath(),另一个是:getAbsolutePath(),可以通过File类的实例调用这两个方法例如file.getAbsolutePath()其中file是File的实例对象 。下面是一个具体例子:
public class PathTest
{
public static void main(String[] args)
{
File file = new File(".\\src\\baidu");
System.out.println(file.getAbsolutePath());
try
{
System.out.println(file.getCanonicalPath());
} catch (IOException e)
{
e.printStackTrace();
}
}
}
getAbsolutePath()和getCanonicalPath()的不同之处在于,getCanonicalPath()得到的是一个规范的路径,而getAbsolutePath()是用构造File对象的路径+当前工作目录 。例如在上面的例子中.(点号)代表当前目录 。getCanonicalPath()就会把它解析为当前目录但是getAbsolutePath()会把它解析成为目录名字(目录名字是点号) 。
下面是上面程序在我电脑上的输出:
G:\xhuoj\konw\.\src\baidu
G:\xhuoj\konw\src\baidu
2. java中获取文件路径的几种方式 获取当前类的所在工程路径;如果不加“/”File f = new File(this.getClass().getResource("").getPath());System.out.println(f);结果:C:\Documents%20and%20Settings\Administrator\workspace\projectName\bin\com\test获取当前类的绝对路径;第二种:File directory = new File("");//参数为空String courseFile = directory.getCanonicalPath() ;System.out.println(courseFile);结果:C:\Documents and Settings\Administrator\workspace\projectName获取当前类的所在工程路径;第三种:URL xmlpath = this.getClass().getClassLoader().getResource("selected.txt");System.out.println(xmlpath);结果:file:/C:/Documents%20and%20Settings/Administrator/workspace/projectName/bin/selected.txt获取当前工程src目录下selected.txt文件的路径第四种:System.out.println(System.getProperty("user.dir"));结果:C:\Documents and Settings\Administrator\workspace\projectName获取当前工程路径第五种:System.out.println( System.getProperty("java.class.path"));结果:C:\Documents and Settings\Administrator\workspace\projectName\bin获取当前工程路径 。
3. java 根据文件获取文件名及路径的方法 我写了一段遍历某个文件查找指定文件的,你自己改成你需要的功能 。
import java.io.File;
import java.util.HashMap;
public class Test1 {
static HashMapfilelist=new HashMap();
/**
* 递归方法
* @param path 文件路径
*/
public static void find(String path){
File file=new File(path);
File[] files = file.listFiles();
//如果文件数组为null则返回
if (files == null)
return;
for (int i = 0; i if (files[i].isDirectory()) {
//判断是不是文件夹,如果是文件夹则继续向下查找文件
find(files[i].getAbsolutePath());
} else {
【java获取文件的路径怎么写】//记录文件路径
String filePath = files[i].getAbsolutePath().toLowerCase();
//记录文件名
String fileName=files[i].getName().toLowerCase();
// System.out.println("---"+strFileName);
filelist.put(fileName, filePath);
}
}
}
public static void main(String[] args) {
//需要遍历的路径,也就是你要查找文件所在的路径
String path="D:\\kpi\\";
find(path);
System.out.println("kpi.9的路径:"+filelist.get("kpi.9"));
//输出结果:d:\kpi\kpi.9
}
}
4. java 如何获取文件路径 public void doGet(HttpServletRequest request ,HttpServletResponse response )
throws ServletException ,IOException{
OutputStream out;//输出响应正文的输出流
InputStream in; //读取本地文件的输入流
//获取filename 请求参数