On the problem of reading file and relative path in Java

1、 For reading files in Java projects

1. Use system or system properties object

① Directly use string relativeypath = system getProperty("user.dir");

② Using the properties object

Let's go through the properties of the system first:

This is the attribute of the system, so it's actually around using user Dir attribute to get the true path of the current project

Through string relativeypath = properties getProperty("user.dir"); obtain

The real path of the project log4jproj on my own computer is:

user. dir--------------D:\Develop\workspace\ws_ self\10_ ws_ eclipse_ j2ee_ mars\Log4jProj

In fact, way ① and way ② have the same meaning and the same goal

2. The second method: use the class loader of the current class to obtain the classloader

First, let's review how to obtain class bytecode instances in three ways: (for example, my class is demo)

① Demo. class

② Class. Forname ("full name of class")

③ Using the instance object of demo, call the getClass () method of the object to obtain the class instance of the object

After reviewing how to get the class bytecode instance, let's review how to get the classloader object

① Demo. class. getClassLoader()

② Class. Forname ("full name of class") getClassLoader()

③ Assume that the demo is an instanced object of the demo getClass(). getClassLoader()

④ It is obtained through the getcontextclassloader () method of the thread object

Thread. currentThread(). getContextClassLoader()

Get to the point:

With the classloader object, we can use the classloader object to get the files in the Java project

First, let's take a look at my current project directory structure

And the directory structure of the actual file

The requirement is that test needs to read log4j Path to the properties file

Two methods of classloader are used, one is static and the other is non-static

Output results:

Remember, the getsystemresource method here obtains the URL object and needs to call the getpath () method to obtain the path

1. When just get log4j The properties file can be used to input the stream in the following two ways

① Still using classloader, there are two methods, one is static and the other is non static

② After wrapping through a file file, create a new input stream

The method of creating file03 is not recommended, because if the getsystemresource method does not get the file, it will get

If the URL object is null, calling getpath() again will report an error

If you have a file object, you can directly create a stream, which will not be repeated here

The above discussion on reading file and relative path of files in Java is all the content shared by Xiaobian. I hope it can give you a reference and support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>