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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9658297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:44:10  来源:igfitidea点击:

Java - How to create a file in a directory using relative Path

java

提问by Sore Finger Tips

I want to create a file in a new directory using the relative path. Creating the directory "tmp" is easy enough.

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

However, when I create the file, it is just located in the current directory not the new one. The code line is below.

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

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

Have tried this also:

也试过这个:

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

Clearly I'm misunderstanding how this method works. Your assistance is greatly appreciated.

显然我误解了这种方法的工作原理。非常感谢您的帮助。

EDIT: added currently used code line as well as the one I think might work for a relative path to clear up confusion.

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

采纳答案by Stanislav Levental

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

BTW: For testing use @Rule and TemporaryFolder class to create temp files or folders

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

回答by Joni

You can create paths relative to a directory with the constructors that take two arguments: http://docs.oracle.com/javase/6/docs/api/java/io/File.html

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

For example:

例如:

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

By the way, the backslash "\" can be used only on Windows. In almost all cases you can use the portable forward slash "/".

顺便说一下,反斜杠“\”只能在 Windows 上使用。在几乎所有情况下,您都可以使用便携式正斜杠“/”。

回答by Mayank

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

回答by Daniel Adenew

Let say you have "Local-Storage"on your project folder and you want to put a text or whatever file using file write.

假设您的项目文件夹中有“Local-Storage”,并且您想使用file write放置文本或任何文件。

  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 );