簡體   English   中英

Java - 如何使用相對路徑在目錄中創建文件

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

我想使用相對路徑在新目錄中創建一個文件。 創建目錄“tmp”很簡單。

但是,當我創建文件時,它只是位於當前目錄而不是新目錄中。 代碼行如下。

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

也嘗試了這個:

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

顯然,我誤解了這種方法的工作原理。 非常感謝您的幫助。

編輯:添加了當前使用的代碼行以及我認為可能用於清除混淆的相對路徑的代碼行。

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

BTW:為了測試,使用@Rule和TemporaryFolder類來創建臨時文件或文件夾

您可以使用帶有兩個參數的構造函數創建相對於目錄的路徑: http//docs.oracle.com/javase/6/docs/api/java/io/File.html

例如:

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

順便說一句,反斜杠“\\”只能在Windows上使用。 在幾乎所有情況下,您都可以使用便攜式正斜杠“/”。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM