簡體   English   中英

從另一個目錄讀取.txt文件

[英]Reading .txt file from another directory

我正在運行的代碼在/Test1/Example 如果需要在/Test1讀取.txt文件,如何使Java返回目錄樹的第1級,然后讀取我的.txt文件

我已經搜索/谷歌搜索,但是找不到在其他位置讀取文件的方法。

我正在/Test1/Test2/testing.htm的.htm文件中運行Java腳本。 它說腳本src=" " 我要在報價中加上什么以使其從位於/Test1/example.txt文件中/Test1/example.txt

在Java中,可以使用getParentFile()遍歷樹。 因此,您在/ Test1 / Example目錄中啟動了程序。 您想將新文件寫為/Test1/Example.txt

    File currentDir = new File(".");
    File parentDir = currentDir.getParentFile();
    File newFile = new File(parentDir,"Example.txt");;

顯然,有多種方法可以做到這一點。

我也有類似的經歷。 我的要求是:我在目錄“輸入”下有一個名為“ sample.json”的文件,在目錄“ testcase”下有一個名為“ JsonRead.java”的java文件。 因此,整個文件夾結構將類似於untitled / splunkAutomation / src,在此下,我將輸入文件夾testcase。

編譯完程序后,您可以在名為“ out / production / yourparentfolderabovesrc / input”的文件夾下看到名為“ sample.json”的輸入文件副本,以及在名為“ out / production”的文件夾下的名為“ JsonRead.class”的類文件。 / yourparentfolderabovesrc / testcase”。 因此,在運行時,Java實際上將引用這些文件,而不是我們在“ src”下的實際.java文件。

因此,我的JsonRead.java看起來像這樣,

package testcase;
import java.io.*;
import org.json.simple.JSONObject;

public class JsonRead{
public static void main(String[] args){
java.net.URL fileURL=JsonRead.class.getClass().getResource("/input/sample.json");
System.out.println("fileURL: "+fileURL);
File f = new File(fileURL.toURI());
System.out.println("fileIs: "+f);
}
}

這將為您提供輸出,如fileURL:file:/ C:/Users/asanthal/untitled/out/production/splunkAutomation/input/sample.json fileIs:C:\\ Users \\ asanthal \\ untitled \\ out \\ production \\ splunkAutomation \\輸入\\ sample.json

您應該能夠使用父目錄引用“ ../”

您可能需要在OS上進行檢查,以確定應該使用['\\'而不是'/']的目錄分隔

在Java中創建File對象時,可以為其指定路徑名。 您可以使用絕對路徑名,也可以使用相對路徑名。 使用絕對值做您想要的事情將需要:

File file = new File("/Test1/myFile.txt");
if(file.canRead())
{
    // read file here
}

如果要從/ Test1 /示例位置運行,請使用親戚路徑:

File file = new File("../myFile.txt");
if(file.canRead())
{
    // read file here
}

它為我工作。 我將所有類都保存在一個文件夾中,但是我需要從我的類文件夾的父目錄中讀取輸入文件。 這完成了工作。

String FileName = "Example.txt";

File parentDir = new File(".."); // New file (parent file ..)   
File newFile = new File(parentDir,fileName); //open the file

暫無
暫無

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

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