Java - 如何使用相对路径在目录中创建文件

30

我想使用相对路径在一个新目录中创建文件。创建目录"tmp"很容易。

但是,当我创建文件时,它只会位于当前目录而不是新目录中。以下是代码行。

    File tempfile = new File("tempfile.txt");

我也尝试过这个方法:

    File tempfile = new File("\\user.dir\\tmp\\tempfile.txt");

很明显我对这个方法的工作原理有误解。非常感谢您的帮助。

编辑:添加了目前使用的代码行以及我认为可以用于相对路径的代码行,以消除混淆。


1
上面的代码使用了绝对路径:\user.dir\tmp\tempfile.txt。我不知道这个文件怎么可能在当前目录下创建。请发布相关代码,解释一下您期望它执行什么操作,以及它实际执行了什么操作。 - JB Nizet
1
“..使用相对路径。” 相对于什么? 应用程序? 类的包? 相对论观察者?请注意:a)这是一个构造函数,而不是方法。 b)user.dir不会自动扩展。 c)通过魔法进行编程很少奏效,请尝试阅读文档。 - Andrew Thompson
4个回答

41
File dir = new File("tmp/test");
dir.mkdirs();
File tmp = new File(dir, "tmp.txt");
tmp.createNewFile();

顺便说一句:为了进行测试,请使用@Rule和TemporaryFolder类来创建临时文件或文件夹。


4
提醒一下(也许你不知道),Sun(或者说Oracle)有非常好的API文档。一旦你学会理解和使用它们,它们可以节省大量时间。例如,如果您查看File类的各种构造函数,可能已经找到了解决您具体问题的方法:http://docs.oracle.com/javase/6/docs/api/java/io/File.html - claymore1977

5

您可以使用带有两个参数的构造函数,相对于目录创建路径:http://docs.oracle.com/javase/6/docs/api/java/io/File.html

例如:

File tempfile = new File("user.dir/tmp", "tempfile.txt");

顺便提一下,反斜杠 "\" 只能在 Windows 上使用。在几乎所有情况下,您可以使用可移植的正斜杠 "/"。


6
File.separator 发生了什么事情? - Manish
1
在几乎所有情况下,您应该使用可移植的斜杠“/”。在每种情况下,您都应该使用接受File(父级)和String(文件名)的File构造函数,或者使用System.getProperty(“file.separator”)。 - Andrew Thompson
@Manish 应该全部小写。 - Andrew Thompson
@AndrewThompson 我指的是 File 类的 separator 属性 - Manish
哦,那个分隔符!既然是一个常量,我本来以为它应该是File.SEPARATOR的 - 这该死的Sun公司。;) 谢谢你澄清这一点。 - Andrew Thompson
谢谢,将“应该”更改为“可以”。正斜杠在当前所有主要操作系统上都被接受作为文件分隔符,除了OpenVMS。在OpenVMS上,JRE具有带斜杠的路径映射。 - Joni

2
String routePath = this.getClass().getClassLoader().getResource(File.separator).getPath();
System.out.println(routePath);

/*for finding the path*/
String newLine = System.getProperty("line.separator");
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(routePath+File.separator+".."+File.separator+"backup.txt"), true));
/*file name is backup.txt and this is working.*/

0
假设您的项目文件夹中有一个名为"Local-Storage"的文件夹,并且您想要使用文件写入来放置文本或任何文件。
  File file = new File(dir,fileName ); //KEY IS DIR ex."./local-storage/" and fileName='comp.html'

        // if file doesnt exists, then create it 
        if ( ! file.exists( ) )
        {
            file.createNewFile( );
        }

        FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
        BufferedWriter bw = new BufferedWriter( fw );
        bw.write( text );

1
为什么不关闭 BufferedWriter? - jcomouth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接