一、背景
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.结果(这样就读取出来了)
七、结束
今天就整理到这里吧,晚安,各位!!!