从另一个目录中读取.txt文件
我正在运行的代码位于/Test1/Example
。如果我需要阅读/Test1
中的.txt文件,我该如何让Java在目录树中返回1级,然后读取我的.txt文件从另一个目录中读取.txt文件
我已经搜索/搜索了并且一直未能找到阅读不同位置的文件的方式。
我在位于/Test1/Test2/testing.htm的.htm文件中运行java脚本。它说脚本src=" "
。我会把这些报价放在/Test1/example.txt
的文件中。
您应该能够使用的“../”
父目录参考您可能需要做OS的检查,以确定您应该使用哪一个目录分离[‘\’相比,“/ ']
当您在Java中创建File
对象时,可以为其指定一个路径名。您可以使用绝对路径名或相对路径名。使用绝对做你想做的需要:
File file = new File("/Test1/myFile.txt");
if(file.canRead())
{
// read file here
}
使用亲戚的路径,如果你想从位置运行/测试1 /例:
File file = new File("../myFile.txt");
if(file.canRead())
{
// read file here
}
如果我在.html文档中运行java脚本,该怎么办?
@Jason - 完全不同的问题。可能要编辑你的问题以澄清你在做什么。 – justkt 2011-03-02 17:36:23
在Java中,你可以使用getParentFile()遍历在树上。所以你在/ Test1/Example目录下启动了你的程序。并且您想要将新文件写入/Test1/Example.txt
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
File newFile = new File(parentDir,"Example.txt");;
显然有多种方法可以执行此操作。
它为我工作。我将所有的类保存在一个文件夹中,但我需要从我的classes文件夹的父目录中读取输入文件。这完成了这项工作。
String FileName = "Example.txt";
File parentDir = new File(".."); // New file (parent file ..)
File newFile = new File(parentDir,fileName); //open the file
我有过类似经历。 我的要求是:我有一个名为“sample.json”的目录下的“输入”,我有我的java文件名为“JsonRead.java”目录下的“testcase”。所以,整个文件夹结构将会像untitled/splunkAutomation/src一样,并且在这之下我有文件夹输入,testcase。
在编译程序后,您可以在名为“out/production/yourparentfolderabovesrc/input”的文件夹下以及名为“JsonRead.class”的类文件下看到名为“sample.json”的输入文件副本“出/生产/ yourparentfolderabovesrc /测试用例”。所以,在运行时,Java实际上将这些文件引用,而不是我们实际的.java文件在“src”下。
所以,我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输出:文件:/ C:/用户/ asanthal /无/出/生产/ splunkAutomation/input/sample.json fileIs:C:\ Users \ asanthal \ untitled \ out \ production \ splunkAutomation \ input \ sample.json
试试这个 - '../ Test1/Example.txt' – Mahesh 2011-03-02 14:08:46
我想看到你写的代码 – Reno 2011-03-02 14:08:55
听起来像你在谈论Javascript,而不是Java? – justkt 2011-03-02 17:37:19