21

.jarファイルと同じフォルダーにあるファイルから読み取る方法はありますか?割り当てを提出するときにファイルから読み取らなければならないJavaプログラムを作成しようとしています。裏返してファイルやプログラムがどこに保持されるかわからないので、保持されているファイルのディレクトリをエンコードできないと思います。これは可能ですか?問題は、LinuxサーバーであるCSXホストサーバーにファイルをアップロードし、そこから実行する必要があることです。ファイルの前にパスを配置しないと、現在のフォルダーの場所が検索されますか?

4

8 に答える 8

25

次の方法で、特定のクラスを含む JAR ファイルの場所を取得できます。

URL url = thisClass.getProtectionDomain().getCodeSource().getLocation();

そこから、目的のファイルへの URL を簡単に関連付けることができます。

于 2013-02-20T09:24:30.983 に答える
20

コメントに記載されているように、これは、jar があるディレクトリからコマンドを実行した場合にのみ機能します。

(デスクトップ アプリケーションのコンテキストで)
の現在のディレクトリにあるファイルにアクセスするにはjarpathファイルの先頭にドットを付ける必要があります。例:

String path = "./properties.txt";
FileInputStream fis = new FileInputStream(path);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
// Read the file contents...

この例ではproperties.txtjar.
このファイルは、に含まれるプログラムによって読み取られますjar

編集:ファイル名は変更されないと言っていましたが、ハードコードすることを好む場合は、事前に名前を知っていれば、この答えが適用されます。

于 2013-02-19T21:47:09.870 に答える
3

入力ファイル名をハードコーディングでき、コードを含む jar と常に同じディレクトリに存在することがわかっている場合、これは機能するはずです。

public static void main(String[] args) {

    try {
        // Determine where the input file is; assuming it's in the same directory as the jar
        String fileName = "input.txt";
        File jarFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        String inputFilePath = jarFile.getParent() + File.separator + fileName;         
        FileInputStream inStream = new FileInputStream(new File(inputFilePath));

        try {

            // Read in the contents of the input file in a single gulp
            FileChannel fc = inStream.getChannel();
            MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0,
                    fc.size());

            // Do something with the read in data
            System.out.println(Charset.defaultCharset().decode(bb)
                    .toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            inStream.close();
        }

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

}
于 2013-02-19T22:30:57.923 に答える
1

「自己完結型」にするには、リソースをJar内に配置します。次に、次のようなものを使用して URL を取得できる(読み取り専用)埋め込みリソースになります。

URL url = this.getClass().getResource("/path/to/the.resource");
于 2013-02-20T01:14:52.963 に答える
1

jarファイルへのクリーンなディレクトリパスを取得する方法は次のとおりです(EJPの回答に基づく):

URL url = IssueInfoController.class.getProtectionDomain().getCodeSource().getLocation();
String urlString = url.toString();
int firstSlash =  urlString.indexOf("/");
int targetSlash = urlString.lastIndexOf("/", urlString.length() - 2) + 1;

return urlString.substring(firstSlash, targetSlash) + YOUR_FILE;
于 2015-03-09T13:16:33.600 に答える
0

あなたのコメントに基づいて、アップロードされたファイルの絶対パスをjarに渡すのが最善の解決策だと思います。

パスをコマンド ライン引数として jar に渡すことができます。パスとファイル名は変更されず、Linux から実行しているため、.sh スクリプトを作成して実行できます。

#!/bin/bash    
java -jar myjar.jar /path/to/file/filename.txt

これにより、ファイル パスまたはファイル名を jar にハードコーディングする必要がなくなります。

于 2013-02-19T21:14:38.703 に答える
-1
public class TestClassLoaderAccess {
    public static void main(String[] argv) {
        TestClassLoaderAccess me = new TestClassLoaderAccess();
        ClassLoader myLoader = me.getClass().getClassLoader();
        System.out.println(myLoader.getClass().getSuperclass().getName());
        java.net.URLClassLoader myUrlLoader = (java.net.URLClassLoader) myLoader;
        java.net.URL resource = myUrlLoader.findResource("TestClassLoaderAccess.class");
        System.out.println(resource.toString());
    }
}

それを実行する:

C:\JavaTools>javac TestClassLoaderAccess.java

C:\JavaTools>java TestClassLoaderAccess
java.net.URLClassLoader
file:/C:/JavaTools/TestClassLoaderAccess.class

C:\JavaTools>

(最初のprintlnは、クラスローダーがURLClassLoaderのサブクラスであることを証明するためのものです。)

于 2013-02-19T22:03:42.417 に答える