简体   繁体   English

如何从jar读取外部文本文件

[英]How to read an external text file from jar

I have a text file that gets written to a network folder and I want my users to be able to click on a jar file which will read in the text file, sort it, and output a sorted file to the same folder. 我有一个写入网络文件夹的文本文件,我希望我的用户能够单击jar文件,该jar文件将读取该文本文件,对其进行排序,然后将排序后的文件输出到同一文件夹。 But I'm having trouble formatting the syntax of the InputStream to read the file in. 但是我在格式化InputStream的语法以读取文件时遇到麻烦。

When I use a FileReader instead of an InputStreamReader the following code works fine in eclipse, but returns empty when run from the jar. 当我使用FileReader而不是InputStreamReader ,以下代码在eclipse中工作正常,但是从jar运行时返回空。 When I change it to InputStream like my research suggests - I get a NullPointerException like it can't find the file. 当像我的研究建议那样将其更改为InputStream -我收到了NullPointerException就像找不到文件一样。

Where did I go wrong? 我哪里做错了? :) :)

public class sort {

    /**
     * @param args
     */
    public static void main(String[] args) {
        sort s = new sort();
        ArrayList<String> farmRecords = new ArrayList<String>();
        farmRecords = s.getRecords(); 

        String testString = new String(); 
        if(farmRecords.size() > 0){
            //do some work to sort the file

        }else{
            testString = "it didn't really work"; 
        }
        writeThis(testString); 
    }



public ArrayList<String> getRecords(){
        ArrayList<String> records = new ArrayList(); 
        BufferedReader br; 
        InputStream recordsStream = this.getClass().getResourceAsStream("./input.IDX");
        try {

            String sCurrentLine;
            InputStreamReader recordsStreamReader = new InputStreamReader(recordsStream);
            br = new BufferedReader(recordsStreamReader);
            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine); 
            }
            br.close();

        } catch (IOException e) {
            e.printStackTrace();
        } 

        return records; 
}

private static void writeThis(String payload){
    String filename = "./output.IDX"; 
    try {
        BufferedWriter fr = new BufferedWriter(new FileWriter(filename));
        fr.write(payload);
        fr.close();
    } catch (IOException e) {

        e.printStackTrace();
    }
}

}

getResourceAsStream() loads files from the classpath. getResourceAsStream()从类路径加载文件。 If you are running this from the command line, you would need the current directory ( . ) on the classpath. 如果从命令行运行,则需要在类路径上使用当前目录( . )。 If you want to load arbitrary files from the file system, you should use FileInputStream (or FileReader to save having to subsequently wrap the input stream in a reader). 如果要从文件系统加载任意文件,则应使用FileInputStream (或FileReader来节省随后将输入流包装到阅读器中的麻烦)。

Using a FIS to get a file inside a jar will not work since the file is not on the file system per se. 由于文件本身不在文件系统上,因此无法使用FIS在jar中获取文件。 You should use getResrouceAsStream() for that. 您应该为此使用getResrouceAsStream()。

Also, to access a file inside a jar, you must add an "!" 另外,要访问jar中的文件,您必须添加“!” to the file path. 到文件路径。 Is the file inside the jar? 文件在罐子里吗? If not, then try a script to start the jar after passing the classpath: 如果不是,请在传递类路径后尝试使用脚本启动jar:

start.sh

    java -cp .:your.jar com.main.class.example.run

Execute this script (on linux) or modify it as per your platform. 根据您的平台执行此脚本(在Linux上)或对其进行修改。

Also, you can use the following code to print out the classpath. 另外,您可以使用以下代码打印出类路径。 This way you can check whether your classpath contains the file? 这样,您可以检查您的类路径是否包含文件?

ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();

    // Get the URLs
    URL[] urls = ((URLClassLoader) sysClassLoader).getURLs();

    for (int i = 0; i < urls.length; i++) {
        System.out.println(urls[i].getFile());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM