2017-04-08 55 views
0

如何寫入或讀取任何類型的文件(用於示例.txt文件)與config.property文件的資源文件夾關聯,但不使用絕對路徑文件。如何寫任何類型的文件(例如txt文件)與config.property文件夾的資源,但不使用絕對路徑文件中的Java

我試圖解決這個象下面這樣:

ClassLoader classLoader = Setting.class.getClassLoader(); 
Setting setting = new Setting(); 

try (InputStream resourceAsStream = classLoader.getResourceAsStream("config.properties")) { 
    setting.load(resourceAsStream); 
} 

String readFileName = setting.getValue("pathSource.txt"); 
String writeFileName = setting.getValue("outPutPathSourceFile.txt"); 

String s = System.getProperty("line.separator"); 

File readFile = new File("./src/main/resources" + File.separator + "pathSource.txt"); 
File writeFile = new File("./src/main/resources" + File.separator + "outPutPathSourceFile.txt"); 

不過,我不希望使用./src/main/resources前綴。

+1

所以基本上,你想知道是否有資源目錄的特殊映射/佔位符? – Sheinbergon

+0

歡迎來到So.你的意思是像'System.getProperty(「user.dir」)+「/ src/main/resources」'? – c0der

+0

是的,非常像System.getProperty(「user.dir」)+「/ src/main/resources」 但沒有強制使用此字符串「/ src/main/resources」 –

回答

0

可以讀取資源(類路徑中的文件,可能位於jar中),但不打算寫入。您可以將它們用作模板以在文件系統上創建初始副本。 - Joop Eggen

+0

對不起,愚蠢的問題。喬普是100%的權利 –

0

如果你的文件位於resources下,你能夠訪問它想:

檔案文件=新的文件(ClassLoader.getResource方法,(文件名).getFile());

如果你使用Spring,你可以使用ResourceUtils.getFile()

文件文件= ResourceUtils.getFile( 「類路徑:文件名」)

UPDATE:

如果我理解正確,你想讀取位於你的src/main/resources下的文件而沒有相對路徑使用/src/main/resources

我創建小的演示:

public class ReadResourceFile { 
    public static void main(String[] args) throws IOException { 
     String fileName = "webAutomationConfig.xml"; 
     ClassLoader classLoader = ReadResourceFile.class.getClassLoader(); 
     File file = new File(classLoader.getResource(fileName).getFile()); 

     System.out.println("File exists: " + file.exists()); 

     String content = new String(Files.readAllBytes(file.toPath())); 
     System.out.println(content); 
    } 
} 

輸出:

File exists: true 
<?xml version="1.0" encoding="utf-8"?> 
<config> 
    <baseUrl>https://www.gmail.com</baseUrl> 
</config> 

項目結構:

enter image description here

+0

不,我想使用位於資源中的文件,我怎樣才能做到這一點: 「/ src/main/resources」 pc但是這個 - > File file = new File(classLoader.getResource(fileName).getFile ));使用progect文件夾中的文件 –

+0

@ВарданМатевосян我更新了我的答案。 –

+0

getFile()產生一個NullPointerException oooo –

相關問題