java(包括springboot)读取resources下⽂件⽅式实现本⽂主要介绍了java(包括springboot)读取resources下⽂件⽅式实现,分享给⼤家,具体如下:
1、使⽤项⽬内路径读取,该路径只在开发⼯具中显⽰,类似:src/main/resources/resource.properties。只能在开发⼯具中使⽤,部署之后⽆法读取。(不通⽤)
File file = new File("src/main/resources/resource.properties");
@Test
public void testReadFile2() throws IOException {
File file = new File("src/main/resources/resource.properties");
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String data = null;
while((data = br.readLine()) != null) {
System.out.println(data);
}
br.close();
isr.close();
fis.close();
}
2、使⽤org.springframework.util.ResourceUtils,读取。在linux环境中⽆法读取。(不通⽤)
File file = File("classpath:resource.properties");
FileInputStream fis = new FileInputStream(file);
@Test
public void testReadFile3() throws IOException {
File file = File("classpath:resource.properties");
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String data = null;
while((data = br.readLine()) != null) {
System.out.println(data);
}
br.close();
isr.close();
fis.close();
}
3、使⽤io.ClassPathResource,各种环境都能读取。(通⽤)
Resource resource = new ClassPathResource("resource.properties");
InputStream is = InputStream();
@Test
public void testReadFile() throws IOException {
//  ClassPathResource classPathResource = new ClassPathResource("resource.properties");
Resource resource = new ClassPathResource("resource.properties");
InputStream is = InputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String data = null;
while((data = br.readLine()) != null) {
System.out.println(data);
}
resource和autowired注解的区别br.close();
isr.close();
is.close();
}
4、结合spring注解,使⽤io.ResourceLoader;类的注解。(通⽤)
package p;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.st.context.SpringBootTest;
import io.Resource;
import io.ResourceLoader;
import st.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class EttpCustomApplicationTests {
@Autowired
ResourceLoader resourceLoader;
@Test
public void testReaderFile() throws IOException {
Resource resource = Resource("classpath:resource.properties");
InputStream is = InputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String data = null;
while((data = br.readLine()) != null) {
System.out.println(data);
}
br.close();
isr.close();
is.close();
}
}
到此这篇关于java(包括springboot)读取resources下⽂件⽅式实现的⽂章就介绍到这了,更多相关java 读取resources内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。