目标文件放在项目的resources文件夹下,文件名叫 1234.txt(文件名需要用数字或字母,用汉字会读取不到):
项目install之后,可以看到文件会到target文件夹下:
方法一:
String filePath = "/1234.txt";
InputStream inputStream = FileUtil.class.getResourceAsStream(filePath);
方法二:
String filePath = "/1234.txt";
String path = FileUtil.class.getResource(filePath).getPath();
InputStream fileInputStream = new FileInputStream(path);
方法三:这种方式文件路径path初始不带 / 杠
String filePath = "1234.txt";
InputStream inputStream = FileUtil.class.getClassLoader().
getResourceAsStream(filePath);
方法四: 这种方式文件路径path初始不带 / 杠
String filePath = "1234.txt";
String path = Thread.currentThread().getContextClassLoader().
getResource(filePath).getPath();
InputStream fileInputStream = new FileInputStream(path);
方法五:System.getProperty 先拿项目根路径,再拼接target/classes 以及文件路径
String filePath = "/1234.txt";
String relativelyPath = System.getProperty("user.dir");
InputStream fileInputStream = new FileInputStream(relativelyPath + "/target/classes/" + filePath);
方法六: Paths.get("").toAbsolutePath() 先拿项目根路径,再拼接target/classes 以及文件路径
String filePath = "/1234.txt";
Path path = Paths.get("").toAbsolutePath();
InputStream fileInputStream = new FileInputStream(path + "/target/classes/" + filePath);