2011-03-02 61 views
1

我正在運行的代碼位於/Test1/Example。如果我需要閱讀/Test1中的.txt文件,我該如何讓Java在目錄樹中返回1級,然後讀取我的.txt文件從另一個目錄中讀取.txt文件

我已經搜索/搜索了並且一直未能找到閱讀不同位置的文件的方式。

我在位於/Test1/Test2/testing.htm的.htm文件中運行java腳本。它說腳本src=" "。我會把這些報價放在/Test1/example.txt的文件中。

+0

試試這個 - '../ Test1/Example.txt' – Mahesh 2011-03-02 14:08:46

+1

我想看到你寫的代碼 – Reno 2011-03-02 14:08:55

+0

聽起來像你在談論Javascript,而不是Java? – justkt 2011-03-02 17:37:19

回答

1

您應該能夠使用的「../」

父目錄參考您可能需要做OS的檢查,以確定您應該使用哪一個目錄分離[‘\’相比,「/ ']

1

當您在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 
} 
+0

如果我在.html文檔中運行java腳本,該怎麼辦?

1

我有過類似經歷。 我的要求是:我有一個名爲「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

相關問題