关于java读取文件以及文件路径的总结

一、背景

1.首先得明确一点,在本地读取文件和在服务器上读取的方式不一样,这就是因为什么你的代码在本地写的很对,但是到服务器上的时候就可能不太好使了,下面我就总结下本地读取文件以及文件的路径和服务器上面读取文件以及文件路径的区别,下面我们就进入正题。

二、测试的项目结构图

1.结构图

三、第一种方式

1.testdemo.java

public class testdemo {
    public static void main(String[] args) {
        System.out.println(System.getProperty("user.dir"));
    }
}

2.结果(打印的是项目的名字和工作空间)

E:\springbootworkspace\springboot-pagehelper

四、第二种方式

1.testdemo.java

public class testdemo {
    public static void main(String[] args) {
        String basePath = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
        System.out.println(basePath);
    }
}

1.1.结果(这是在本地),会报空指针的错误。

Exception in thread "main" java.lang.NullPointerException
	at com.example.springbootpagehelper.controller.testdemo.main(testdemo.java:10)

1.2.结果(在服务器上面)

private static void test() {
	String basePath = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
	String path = new File(basePath).getAbsolutePath();
	System.out.println(path);
}

注意:在服务器上面要这么配合着使用才不会报空指针的问题。获取到的路径如下:

以上是获取路径的方法。

五、读取jar包的资源

1.在resources下面添加一个文件config/student.txt(student.txt中的内容是 i am a student)

@SpringBootApplication
public class SpringbootPagehelperApplication {
	private static final String path= "config/student.txt";

	public static void main(String[] args) throws IOException {
		String test = test();
		System.out.println(test);
		SpringApplication.run(SpringbootPagehelperApplication.class, args);
	}
	private static String test() throws IOException {
		InputStream in=SpringbootPagehelperApplication.class.getClassLoader().getResourceAsStream(path);
		Reader f = new InputStreamReader(in);
		BufferedReader fb = new BufferedReader(f);
		StringBuffer sb = new StringBuffer("");
		String s = "";
		while((s = fb.readLine()) != null) {
			sb = sb.append(s);
		}
		return sb.toString();
	}
}

六、打成jar包进行测试

1.结果(这样就读取出来了)

 七、结束

今天就整理到这里吧,晚安,各位!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值