jar包中读取文件系统绝对路径,相对路径,以及jar包内部路径的写法

结论:

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();
		}
	}
}

 

 

 

 

 

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值