从另一个目录中读取.txt文件

我运行的代码在/Test1/Example 。 如果我需要读取/Test1的.txt文件,如何让Java在目录树中返回1级,然后读取我的.txt文件

我搜索/ googled并且无法找到在不同位置读取文件的方法。

我在位于/Test1/Test2/testing.htm的.htm文件中运行java脚本。 它说脚本src=" " 。 我会在引文中添加什么来从位于/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");; 

显然,有多种方法可以做到这一点。

您应该能够使用“../”的父目录引用

您可能需要对操作系统进行检查,以确定应使用[‘\’与’/’进行比较的目录分隔]

在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 } 

我有类似的经历。 我的要求是:我在一个目录“input”下有一个名为“sample.json”的文件,我的目录“testcase”下有一个名为“JsonRead.java”的java文件。 所以,整个文件夹结构就像无标题/ splunkAutomation / src,在这下我有文件夹输入,testcase。

编译完程序后,您可以在名为“out / production”的名称为“out / production / yourparentfolderabovesrc / input”的文件夹下找到名为“sample.json”的输入文件副本,并在名为“out / production”的文件夹下查看名为“JsonRead.class”的类文件/ yourparentfolderabovesrc /测试用例”。 因此,在运行时,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

它对我有用。 我在文件夹中保存了所有类,但是我需要从classes文件夹的父目录中读取输入文件。 这样做了。

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