2017-04-08 56 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 –

相关问题