Home  >  Article  >  Java  >  How to read files using relative paths in java

How to read files using relative paths in java

coldplay.xixi
coldplay.xixiOriginal
2020-09-02 13:06:0013841browse

How to use relative paths to read files in java: 1. Use the file [File file = new File (“src/test.txt”)] method; 2. Use the relative path of the class; 3. Use The class loader of the current thread; 4. Read the files under the web project.

How to read files using relative paths in java

[Related learning recommendations: java basic tutorial

How to read files using relative paths in java:

1. Simple and crude File file = new File(“src/test.txt”);

  @Test
    /**
     * 这种方法 “” 空代表的是 这个Java项目 TestSomeTechnology  由于实际项目在打包后没有src目录 所以这种方法不常用
     */
    public  void  testMethod1() throws IOException{
        File file = new File("src/test.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String len = null;
        while ((len=br.readLine())!=null){
            System.out.println(len);
        }
    }

2. Use the relative path of the class

TestRelativePath.class.getResource(“/test.txt”).getFile()

 @Test
    /**
     * 使用类的相对路径
     * 这种方法 “/” 代表的是bin。  src文件夹和resources 文件夹下的的东西都会被加载到bin下面 因为这两个文件被配置为了source
     */
    public  void  testMethod2() throws IOException{
        File file = new File(TestRelativePath.class.getResource("/test.txt").getFile());
        BufferedReader br = new BufferedReader(new FileReader(file));
        String len = null;
        while ((len=br.readLine())!=null){
            System.out.println(len);
        }
    }

3. Use the class loader of the current thread

Thread.currentThread().getContextClassLoader().getResource(“test.txt”).getFile()

@Test
    /**
     * 这种是通过当前线程的类加载器
     * 这种方法 “ ” 空代表的是bin 。 于是就直接填写test,文件夹下的的东西都会被加载到bin下面,因为这两个文件被配置为了source
     */
    public  void  testMethod3() throws IOException{
        File file = new File(Thread.currentThread().getContextClassLoader().getResource("test.txt").getFile());
        BufferedReader br = new BufferedReader(new FileReader(file));
        String len = null;
        if ((len=br.readLine())!=null){
            System.out.println(len);
        }
    }

4. Read the files under the web project and use getRealPath() to read the

directory as follows:

How to read files using relative paths in java

Read index.jsp

@WebServlet(name = "TestServlet",urlPatterns = "/TestServlet")
public class TestServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
    }
    /**
     *  web工程的根目录是 webRoot, 使用 “/” 代表webroot webroot下面有index.jsp文件
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        File file = new File(getServletContext().getRealPath("/index.jsp"));
        BufferedReader br = new BufferedReader(new FileReader(file));
        String len = null;
        while ((len=br.readLine())!=null){
            System.out.println(len);
        }
    }
}

Read test.txt file

But if we want to read test.txt, we can use the above method

 File file = new File(Thread.currentThread().getContextClassLoader().getResource("test.txt").getFile());

You can also use getRealPath()

However, since the webroot is the root directory, we need to read it from classes: the classes of idea are equivalent to the classpath of esclipse. classes description:

How to read files using relative paths in java

Code:

File file = new File(getServletContext().getRealPath("/WEB-INF/classes/test.txt"));

detailed explanation of getResourceAsStream() method

getResourceAsStream() usage and getResouce () method is the same. After using getResource() to obtain the File file, new FileInputStream(file) has the same effect as getResourceAsStream(). .

The two codes have the same effect

InputStream inputStream1 = new FileInputStream(new File(Thread.currentThread().getContextClassLoader().getResource("test.txt").getFile()));
InputStream inputStream2 = Thread.currentThread().getContextClassLoader().getResourceAsStream("test.txt");

Related recommendations:Programming video course

The above is the detailed content of How to read files using relative paths in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn