首先,java里目录也是文件。 你要做所谓的相对路径,你总要有一个参照点吧? 我们假设你有一个参照点: File file; 那么,你要在它下面创建文件的话: File other = new File(file, "fileName"); other.createNewFile(); 你要在它下面创建文件夹的话: File other = new File(file, "fileName"); other.mkdir(); 如果想在同层目录下建文件,则是这样: File other = new File(file.getParentFile(), "fileName"); 依次类推,你可以在参照点的任何相对位置创建文件和文件夹。
import java.io.File; import java.io.IOException;public class Mineme { public static void main(String[] args) { File f=new File(".");//以当前路径来创建一个File类("."表示当前路径) try { //创建一个“.txt”文件在当前目录下(包的存储目录下)name为文, //件名还会加上随机数 File temp=File.createTempFile("name", ".txt",f); System.out.println(temp.getName()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } __________________________________________________________________________ 如果你要新建文件夹的话: File f = new File(file, "Name"); f.createNewFile();
//先获取当前工作目录路径,再拼接下一级路径 String path = System.getProperty("user.dir")+File.Seperator+"test"; File f = new File(path);
楼主,java里面路径用//,不是WINDOWS里面的\\
public class PathTest { public static void main(String[] args) { System.out.println(System.getProperty("user.dir")); } } //Result: //D:\workspace\YourProjName
lz可以试试 String filepath = "文件目录"; File dir = new File(filepath); if(!dir.exists()){ dir.mkdirs(); //创建文件夹 } //如filepath = "test"; //这在项目的根目录下会创建test文件夹
你要做所谓的相对路径,你总要有一个参照点吧?
我们假设你有一个参照点:
File file;
那么,你要在它下面创建文件的话:
File other = new File(file, "fileName");
other.createNewFile();
你要在它下面创建文件夹的话:
File other = new File(file, "fileName");
other.mkdir();
如果想在同层目录下建文件,则是这样:
File other = new File(file.getParentFile(), "fileName");
依次类推,你可以在参照点的任何相对位置创建文件和文件夹。
这个应该可以了。
import java.io.IOException;public class Mineme
{
public static void main(String[] args) {
File f=new File(".");//以当前路径来创建一个File类("."表示当前路径)
try {
//创建一个“.txt”文件在当前目录下(包的存储目录下)name为文,
//件名还会加上随机数
File temp=File.createTempFile("name", ".txt",f);
System.out.println(temp.getName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
__________________________________________________________________________ 如果你要新建文件夹的话:
File f = new File(file, "Name");
f.createNewFile();
String path = System.getProperty("user.dir")+File.Seperator+"test";
File f = new File(path);
public class PathTest {
public static void main(String[] args) {
System.out.println(System.getProperty("user.dir"));
}
}
//Result:
//D:\workspace\YourProjName
File dir = new File(filepath);
if(!dir.exists()){
dir.mkdirs(); //创建文件夹
}
//如filepath = "test";
//这在项目的根目录下会创建test文件夹
String currentDir = System.getProperty("user.dir");//获取当前目录
try {
String fileName = "test.txt";
FileOutputStream fos = new FileOutputStream(currentDir+File.separator+fileName);
fos.write("Hello".getBytes());
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
如果想获取动态配置的效果,加上一个启动参数-Duser.dir=%project_dir%/config
就这么简单!
当前类.class.getClassLoader().getResource(url).getPath()
url相对的路径