结论:

1.在jar包代码中要使用操作系统的绝对路径,路径以 / 开始。
2.在jar包代码中使用相对路径,起点是jar所在目录。比如说test.jar所处位置为/opt/test/test.jar,那么你在代码中写相对路径:“pathTest/haha.txt”,那么实际指向的位置为/opt/test/pathTest/haha.txt
3.在jar包代码中使用:InputStream inputStream = this.getClass().getResourceAsStream(path) 的写法,不管路径以是否以 / 开始,都是从jar包内部的根目录为起点。

以下是测试代码,代码的最终运行结果是(jar包放在/opt/test/目录进行运行):
1.在/opt/pathTest/文件夹下新建了  test_absolutePath.txt文件
2.在/opt/test/pathTest/文件夹下新建了 test_relativePath.txt 文件
3.成功从/opt/test/test.jar/pathTest/test_injarPath.txt文件中读取出内容
4.和3结果一样

 

 

​
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HttpsURLConnection;
import javax.print.attribute.standard.Severity;

import com.sun.tools.classfile.Annotation.element_value;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion.Static;

public class Test {

	public static void main(String args[]) throws IOException {
		new Test().testPath();
	}
	
	public void testPath(){
		try {
			String path1 = "/opt/pathTest/";
			File file = new File(path1);
			if(!file.exists()){
				file.mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(path1+"test_absolutePath.txt");
			fos.write("hahahhaha".getBytes());
			fos.close();
			
			String path2 = "pathTest/";
			File file2 = new File(path2);
			if(!file2.exists()){
				file2.mkdirs();
			}
			FileOutputStream fos2 = new FileOutputStream(path2+"test_relativePath.txt");
			fos2.write("hahahhaha".getBytes());
			fos2.close();
			
			//jar包内部用读取来测试
			String path3 = "/pathTest/test_injarPath.txt";
			InputStream inputStream = this.getClass().getResourceAsStream(path3);
			byte[] buffer = new byte[1024];
			int n = inputStream.read(buffer);
			System.out.println("form file:" + path3 + " read:" + new String(buffer,0,n));
			inputStream.close();
			
			//jar包内部用读取来测试
			String path4 = "pathTest/test_injarPath.txt";
			inputStream = this.getClass().getResourceAsStream(path4);
			buffer = new byte[1024];
			n = inputStream.read(buffer);
			System.out.println("form file:" + path4 + " read:" + new String(buffer,0,n));
			inputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

 

 

 

 

Logo

助力广东及东莞地区开发者,代码托管、在线学习与竞赛、技术交流与分享、资源共享、职业发展,成为松山湖开发者首选的工作与学习平台

更多推荐