Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 读取类路径中的文件_Java_Spring_File Io_Classpath - Fatal编程技术网

Java 读取类路径中的文件

Java 读取类路径中的文件,java,spring,file-io,classpath,Java,Spring,File Io,Classpath,下面是我想做的,我想知道是否有任何Spring类可以帮助实现。我不必使用spring来解决这个特殊的问题,我只是用其他的东西来实现它 在我的DAO层中,我希望外部化我的sql文件,即每个文件1个sql。我想读取和缓存sql语句,甚至可能作为SpringBean单例。但是在我最初的挣扎中,我遇到了一个问题,就是在类路径中加载一个sql文件 春天有什么可以帮你的吗?我已经看过文件了,但没有什么能让我感到惊讶 这就是我想要的。。但是我无法让它识别文件或者类路径。。。不确定是否需要在applicatio

下面是我想做的,我想知道是否有任何Spring类可以帮助实现。我不必使用spring来解决这个特殊的问题,我只是用其他的东西来实现它

在我的DAO层中,我希望外部化我的sql文件,即每个文件1个sql。我想读取和缓存sql语句,甚至可能作为SpringBean单例。但是在我最初的挣扎中,我遇到了一个问题,就是在类路径中加载一个sql文件

春天有什么可以帮你的吗?我已经看过文件了,但没有什么能让我感到惊讶

这就是我想要的。。但是我无法让它识别文件或者类路径。。。不确定是否需要在applicationContext中定义某些内容

以下是一些似乎不起作用的尝试。。。既有春天的味道,也有爪哇的味道

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")));

有什么想法吗?

改变。作为路径分隔符并使用
getResourceAsStream

reader = new BufferedReader(new InputStreamReader(
    getClass().getClassLoader().getResourceAsStream(
        "com/company/app/dao/sql/SqlQueryFile.sql")));

使用
Class.getResourceAsStream()
vs
ClassLoader.getResourceAsStream
时,请注意前导斜杠。
getSystemResourceAsStream
使用的系统类加载器不是您想要的


我怀疑使用斜杠而不是圆点也适用于
ClassPathResource

尝试让Spring注入它,假设您使用Spring作为依赖项注入框架

在课堂上,做如下操作:

public void setSqlResource(Resource sqlResource) {
    this.sqlResource = sqlResource;
}
然后在应用程序上下文文件中,在bean定义中,只需设置一个属性:

<bean id="someBean" class="...">
    <property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>

Spring应该足够聪明,可以从类路径加载文件,并将其作为资源提供给bean


您还可以查看并将所有SQL存储在属性文件中,只需在需要时分别注入每个SQL即可。有很多选择。

小心前面的/。如果上面的代码是从包com.company.app.dao.sql中的类访问的,那么实际上您只需要在那里使用SqlQueryFile.sql。如果代码是从另一个包访问的,您需要一个前导/oh等一下-您真的需要getClass().getClassLoader().getResourceAsStream()-它是非静态的。我注意到您需要getClass(),但由于某种原因它不起作用。不过我相信它真的很近。看起来应该能用。我得到的春季答案是我想要的,所以我不再追求这个了。谢谢大家的帮助!好的,我将编辑它,为后代使用getClass().getClassLoader()。好的,我知道这是旧的,但它是胶状的。您需要使用(ClassLoader.getSystemClassLoader().getResourceAsStream())或.class.getResourceAsStream()。我很困惑,为什么有人指着这个答案来澄清另一个答案,而它却无法编译。谢谢,这就是我想要的。我对spring还比较陌生,这似乎很管用。不幸的是,我在春季论坛上发布了同样的问题,但没有得到回应+1对stackoverfow。回答得好!那是资源org.springframework.core.io.Resource吗?
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`

}
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`

}