.jarファイルと同じフォルダーにあるファイルから読み取る方法はありますか?割り当てを提出するときにファイルから読み取らなければならないJavaプログラムを作成しようとしています。裏返してファイルやプログラムがどこに保持されるかわからないので、保持されているファイルのディレクトリをエンコードできないと思います。これは可能ですか?問題は、LinuxサーバーであるCSXホストサーバーにファイルをアップロードし、そこから実行する必要があることです。ファイルの前にパスを配置しないと、現在のフォルダーの場所が検索されますか?
8 に答える
次の方法で、特定のクラスを含む JAR ファイルの場所を取得できます。
URL url = thisClass.getProtectionDomain().getCodeSource().getLocation();
そこから、目的のファイルへの URL を簡単に関連付けることができます。
コメントに記載されているように、これは、jar があるディレクトリからコマンドを実行した場合にのみ機能します。
(デスクトップ アプリケーションのコンテキストで)
の現在のディレクトリにあるファイルにアクセスするにはjar
、path
ファイルの先頭にドットを付ける必要があります。例:
String path = "./properties.txt";
FileInputStream fis = new FileInputStream(path);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
// Read the file contents...
この例ではproperties.txt
、jar
.
このファイルは、に含まれるプログラムによって読み取られますjar
。
編集:ファイル名は変更されないと言っていましたが、ハードコードすることを好む場合は、事前に名前を知っていれば、この答えが適用されます。
入力ファイル名をハードコーディングでき、コードを含む 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();
}
}
「自己完結型」にするには、リソースをJar内に配置します。次に、次のようなものを使用して URL を取得できる(読み取り専用)埋め込みリソースになります。
URL url = this.getClass().getResource("/path/to/the.resource");
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;
あなたのコメントに基づいて、アップロードされたファイルの絶対パスをjarに渡すのが最善の解決策だと思います。
パスをコマンド ライン引数として jar に渡すことができます。パスとファイル名は変更されず、Linux から実行しているため、.sh スクリプトを作成して実行できます。
#!/bin/bash
java -jar myjar.jar /path/to/file/filename.txt
これにより、ファイル パスまたはファイル名を jar にハードコーディングする必要がなくなります。
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のサブクラスであることを証明するためのものです。)