读取文件
ResourceUtil 和 BufferedReader 读取 classpath 下的文本文件
读取文件示例
package com.litongjava.open.chat.services;
import java.net.URL;
import org.junit.Test;
import com.litongjava.tio.utils.hutool.FileUtil;
import com.litongjava.tio.utils.hutool.ResourceUtil;
public class RMPRatingServiceTest {
@Test
public void test() {
URL resource = ResourceUtil.getResource("courses_functions_findCourses_parameters_sq_description.txt");
byte[] bytes = FileUtil.readUrlAsBytes(resource);
StringBuilder string = FileUtil.readURLAsString(resource);
}
}
代码示例 读取为List<String> lines
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
URL resource = ResourceUtil.getResource(filePath);
if (resource == null) {
throw new RuntimeException();
}
List<String> lines;
try (InputStream inputStream = resource.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
lines = reader.lines().collect(Collectors.toList());
} catch (IOException e) {
throw new RuntimeException(e);
}
代码示例 读取文件内容为字符串
URL resource = ResourceUtil.getResource("courses_functions_findCourses_parameters_sq_description.txt");
if (resource == null) {
throw new RuntimeException();
}
StringBuilder text = new StringBuilder();
try (InputStream inputStream = resource.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
char[] buffer = new char[1024];
int bytesRead;
while ((bytesRead = reader.read(buffer, 0, buffer.length)) != -1) {
text.append(buffer, 0, bytesRead);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
如果感觉上面的方法繁琐,可以使用下面的代码
import com.litongjava.tio.utils.hutool.FileUtil;
import com.litongjava.tio.utils.hutool.ResourceUtil;
URL resource = ResourceUtil.getResource("courses_functions_findCourses_parameters_sq_description.txt");
StringBuilder text = FileUtil.readURLAsString(resource);
代码示例 读取文件内容为字节数组
URL resource = ResourceUtil.getResource("samples/Blowin_in_the_Wind-16k.pcm");
if (resource == null) {
throw new RuntimeException("Resource not found");
}
try (InputStream inputStream = resource.openStream()) {
byte[] buffer = new byte[1024 * 10];
int bytesRead;
int i = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
//处理bytes
}
} catch (IOException e) {
throw new RuntimeException(e);
}