前提
文件目录如下
/src
/main
/java
/resources
/mydata.txt
目标文件: mydata.txt
如何方便读取该文件内容
-
将文件读取为InputStream
-
从文件读取内容
下面展示了读取文件内容的示例工具
注意:如果文件内容过大,不要使用该工具,应该自己手动处理inputStream
.
使用Spring方式
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
@Component
public class ResourceHelper {
@Autowired
private ResourceLoader resourceLoader;
/**
* 读取文件内容为一整个字符串
*/
public String readString(String resourcePath) throws IOException {
Resource resource = resourceLoader.getResource(resourcePath);
InputStream inputStream = resource.getInputStream();
return IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
}
/**
* 读取文件内容为列表
*/
public List<String> readLines(String resourcePath) throws IOException {
Resource resource = resourceLoader.getResource(resourcePath);
InputStream inputStream = resource.getInputStream();
return IOUtils.readLines(inputStream, StandardCharsets.UTF_8.name());
}
}
使用示例
// 导入上面的ResourceHelper
import xxx.ResourceHelper;
import org.springframework.util.ResourceUtils;
@Component
public class TestDAO {
// 注意,此处添加文件名前缀
public static final String SQL_PATH = ResourceUtils.CLASSPATH_URL_PREFIX
+ "mydata.txt";
@Autowired
private ResourceHelper resourceHelper;
public Object search(String structuredId) throws IOException {
String sql = resourceHelper.readString(SQL_PATH);
// ... 省略处理方式
}
}
不使用Spring的方式
-
编写ClassUtils
public class ClassUtils { public static ClassLoader getDefaultClassLoader() { ClassLoader cl = null; try { // 获取当前线程classLoader cl = Thread.currentThread().getContextClassLoader(); } catch (Throwable ex) { // Cannot access thread context ClassLoader - falling back... } if (cl == null) { // No thread context class loader -> use class loader of this class. // 获取当前类ClassLoader cl = ClassUtils.class.getClassLoader(); if (cl == null) { // getClassLoader() returning null indicates the bootstrap ClassLoader try { // 获取系统默认ClassLoader cl = ClassLoader.getSystemClassLoader(); } catch (Throwable ex) { // Cannot access system ClassLoader - oh well, maybe the caller can live with null... } } } return cl; } }
-
编写工具类
import org.apache.commons.io.IOUtils; public class ResourceUtils { public String readString(String resourcePath) throws IOException { InputStream inputStream = ClassUtils.getDefaultClassLoader() .getResourceAsStream(resourcePath); return IOUtils.toString(inputStream, StandardCharsets.UTF_8.name()); } public List<String> readLine(String resourcePath) throws IOException { InputStream inputStream = ClassUtils.getDefaultClassLoader() .getResourceAsStream(resourcePath); return IOUtils.readLines(inputStream, StandardCharsets.UTF_8.name()); } }
-
使用
@Component public class TestDAO { // 此处直接写文件名 public static final String SQL_PATH = "mydata.txt"; public Object search(String structuredId) throws IOException { String sql = ResourceUtils.readString(SQL_PATH); // ... 省略处理方式 } }