Java 在类路径中读取文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/734671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
read file in classpath
提问by Greg J
Here is what I want to do and I am wondering if there is any Spring classes that will help with implementing. I don't have to use spring for this particular problem, I'm just implementing it with everything else.
这是我想要做的,我想知道是否有任何 Spring 类可以帮助实现。我不必使用 spring 来解决这个特定的问题,我只是用其他所有东西来实现它。
In my DAO layer I want to externalize my sql files aka 1 sql per file. I want to read and cache the sql statement even maybe as a spring bean singleton. But in my initial struggles, I am having a problem just loading a sql file in the classpath...
在我的 DAO 层中,我想外部化我的 sql 文件,也就是每个文件 1 个 sql。我想读取和缓存 sql 语句,甚至可能作为 spring bean 单例。但是在我最初的挣扎中,我在类路径中加载一个 sql 文件时遇到了问题......
Is there anything in spring to help with that? I've been through the documentation but nothing is jumping out at me.
春天有什么东西可以帮助解决这个问题吗?我已经阅读了文档,但没有任何内容让我印象深刻。
Here is kind of what I'm after.. but I can't get it to recognize the file or maybe the classpath... not real sure does something need to be defined in applicationContext?
这是我所追求的......但我无法让它识别文件或类路径......不确定是否需要在applicationContext中定义某些东西?
Here are a couple of attempts that do not seem to work... both spring'ish and just java'ish.
这里有一些似乎不起作用的尝试...... spring'ish和java'ish。
reader = new BufferedReader(new InputStreamReader(new ClassPathResource("com.company.app.dao.sql.SqlQueryFile.sql").getInputStream())
reader = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("com.company.app.dao.sql.SqlQueryFile.sql")));
Any thoughts?
有什么想法吗?
采纳答案by Jon Skeet
Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.
尝试让 Spring 注入它,假设您使用 Spring 作为依赖注入框架。
In your class, do something like this:
在你的课堂上,做这样的事情:
public void setSqlResource(Resource sqlResource) {
this.sqlResource = sqlResource;
}
And then in your application context file, in the bean definition, just set a property:
然后在您的应用程序上下文文件中,在 bean 定义中,只需设置一个属性:
<bean id="someBean" class="...">
<property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>
And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.
Spring 应该足够聪明,可以从类路径加载文件并将其作为资源提供给您的 bean。
You could also look into PropertyPlaceholderConfigurer, and store all your SQL in property files and just inject each one separately where needed. There are lots of options.
您还可以查看PropertyPlaceholderConfigurer,并将所有 SQL 存储在属性文件中,并在需要的地方单独注入每个 SQL。有很多选择。
回答by Jon Skeet
Change . to / as the path separator and use getResourceAsStream
:
改变 。to / 作为路径分隔符并使用getResourceAsStream
:
reader = new BufferedReader(new InputStreamReader(
getClass().getClassLoader().getResourceAsStream(
"com/company/app/dao/sql/SqlQueryFile.sql")));
or
或者
reader = new BufferedReader(new InputStreamReader(
getClass().getResourceAsStream(
"/com/company/app/dao/sql/SqlQueryFile.sql")));
Note the leading slash when using Class.getResourceAsStream()
vs ClassLoader.getResourceAsStream
.
getSystemResourceAsStream
uses the systemclassloader which isn't what you want.
使用Class.getResourceAsStream()
vs时请注意前导斜杠ClassLoader.getResourceAsStream
。
getSystemResourceAsStream
使用系统类加载器,这不是您想要的。
I suspect that using slashes instead of dots would work for ClassPathResource
too.
我怀疑使用斜杠而不是点也可以ClassPathResource
。
回答by Helper
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class readFile {
/**
* feel free to make any modification I have have been here so I feel you
*
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
File dir = new File(".");// read file from same directory as source //
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
// if you wanna read file name with txt files
if (file.getName().contains("txt")) {
System.out.println(file.getName());
}
// if you want to open text file and read each line then
if (file.getName().contains("txt")) {
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(
file.getAbsolutePath());
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(
fileReader);
String line;
// get file details and get info you need.
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
// here you can say...
// System.out.println(line.substring(0, 10)); this
// prints from 0 to 10 indext
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '"
+ file.getName() + "'");
} catch (IOException ex) {
System.out.println("Error reading file '"
+ file.getName() + "'");
// Or we could just do this:
ex.printStackTrace();
}
}
}
}
}`enter code here`
}