The target file is placed in the mytxt file under the resources folder of the project. The file name is file Test.txt:
In fact, you can see that after the project is run, this file is dropped into the target folder:
Get the InputStream of this file:
For example, we write a method to obtain the file stream in FileUtil,
public class FileUtil {
}
① getResourceAsStream
String filePath = "/mytxt/fileTest.txt";
InputStream inputStream = FileUtil.class.getResourceAsStream(filePath);
② getResource + getPath
String filePath = "/mytxt/fileTest.txt";
String path = FileUtil.class.getResource(filePath).getPath();
InputStream fileInputStream = new FileInputStream(path);
③ getClassLoader().getResourceAsStream (note that the file path in this method does not initially have a / bar)
String filePath = "mytxt/fileTest.txt";
InputStream inputStream = FileUtil.class.getClassLoader().getResourceAsStream(filePath);
④ Thread.currentThread().getContextClassLoader().getResource (note that in this way, the file path does not initially have a / bar)
String filePath = "mytxt/fileTest.txt";
String path = Thread.currentThread().getContextClassLoader().getResource(filePath ).getPath();
InputStream fileInputStream = new FileInputStream(path);
⑤ System.getProperty first gets the project root path, and then splices target/classes and file path
String filePath = "/mytxt/fileTest.txt";
String relativelyPath = System.getProperty("user.dir");InputStream fileInputStream = new FileInputStream(relativelyPath + "/target/classes/" + filePath);
⑥ Paths.get("").toAbsolutePath() First get the project root path, then splice target/classes and file path
String filePath = "/mytxt/fileTest.txt";
Path path = Paths.get("").toAbsolutePath();
InputStream fileInputStream = new FileInputStream(path + "/target/classes/" + filePath);
Get the InputStream and do whatever you need to do. Well, that’s it for this article.