Java relative path Read file

Source: Internet
Author: User
Tags relative root directory

Whether you are a novice or a veteran, in the program to read the resource files will always encounter some files can not find the problem, which is related to the Java bottom of the implementation, not a bug, as long as the method is appropriate, the problem can be solved.

Folder structure for the project:

repathtest
├─src
│    └─com
│            └─lavasoft
│                    ├─test
│                    └─res
├─doc

1. Using relative paths in project in Java development tools

In project, the root directory of the relative path is the root folder of project, and this is the Repathtest folder.

The file is created by:

File f = new File("src/com/lavasoft/res/a.txt");

File f = new File("doc/b.txt");

Attention:

Path does not begin with "/";

Out of the IDE environment, this is wrong, not every IDE, but that's what I see.

2. Read package files through Classpath

Read the package file, the path must be a relative classpath path, such as a, located in the package, you can create a byte stream to read a:

InputStream in = ReadFile.class.getResourceAsStream ("/com/lavasoft/res/a.txt");

With a byte stream, you can read the contents of the file.

Attention:

This must begin with a "/";

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.