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

Java-如何使用相对路径在目录中创建文件,java,Java,我想使用相对路径在新目录中创建一个文件。创建目录“tmp”非常简单 但是,当我创建文件时,它只是位于当前目录中,而不是新目录中。代码行在下面 File tempfile = new File("tempfile.txt"); 我也尝试过这一点: File tempfile = new File("\\user.dir\\tmp\\tempfile.txt"); 显然,我误解了这种方法的工作原理。非常感谢你的帮助 编辑:添加了当前使用的代码行以及我认为可能用于相对路径的代码行,

我想使用相对路径在新目录中创建一个文件。创建目录“tmp”非常简单

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

    File tempfile = new File("tempfile.txt");
我也尝试过这一点:

    File tempfile = new File("\\user.dir\\tmp\\tempfile.txt");
显然,我误解了这种方法的工作原理。非常感谢你的帮助


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

您可以使用带两个参数的构造函数创建相对于目录的路径:

例如:

File tempfile = new File("user.dir/tmp", "tempfile.txt");
顺便说一下,反斜杠“\”只能在Windows上使用。在几乎所有情况下,您都可以使用可移植的正斜杠“/”

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

假设您的项目文件夹上有“本地存储”,并且您希望使用文件写入来放置文本或任何文件

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.*/
  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 );

上面的代码使用一个绝对路径:
\user.dir\tmp\tempfile.txt
。我不知道如何在当前目录中创建此文件。发布相关代码,向我们解释您期望它做什么,以及它做什么。”…使用相对路径。“相对于什么?”?申请表?班级的套餐?相对论观察家?注意a)这是一个构造函数,而不是一个方法。b)
user.dir
将不会自动展开。c) “几乎所有情况下,您都应该使用可移植的正斜杠“/”。在任何情况下,您都应该使用接受
文件的
构造函数(父项)和
字符串
(文件名)或者使用
System.getProperty(“file.separator”)
@Manish它应该都是小写。@andrewhompson我指的是
文件
类的名称。哦,那个分隔符!如果它是一个常量,我会希望它是
File.SEPARATOR
-bloody Sun.)感谢您的澄清。正如一个提醒(因为您可能不知道这一点),但是Sun,呃Oracle,有非常好的API文档。一旦你学会理解和驾驭它们,它们就可以节省大量的时间。例如,如果您查看了File类用户可用的各种构造函数,就可以找到特定问题的解决方案:为什么不关闭BufferedWriter?
  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 );