些文件路径时尽量用File.separator进行分割,因为linux和windows系统中/和\格式不一样
使用Spring的Resource读取文件内容source为文件路径Ioutis为tomcate的包len返回读取到的实际长度。返回字符格式的数据
private byte[] abc(String source) throws IOException{
Resource resource = new ClassPathResource(source);
InputStream in = resource.getInputStream();
int length = in.available();
byte[] buffer = new byte[length];
int len=IOUtils.read(in, buffer, 0, length);
return buffer;
}或者用下面的读取sourcePath直接用name/***引用
ClassLoader classLoader = getClass().getClassLoader();
InputStream stream = classLoader.getResourceAsStream(sourcePath);
Scanner scanner = new Scanner(stream); 也可以用 String str= IOUtils.toString(stream, "UTF-8");直接读取
while (scanner.hasNextLine()) { String s = scanner.nextLine();
String[] items = s.split(" +"); //csv文件一般用///t进行分割
if (items.length != 2) { continue; }
appsClassif.put(items[0], Arrays.asList(items[1].split(","))); } }
也可以用
其中/product/.....为resource下面的文件夹
IOUtils为import org.apache.commons.io.IOUtils;
String dmRes = IOUtils.resourceToString("/product/" + productId+ "/skill-dm-" + skillId + ".json", Charset.forName("utf-8"));
将byte[]集合对象转换为字符串对象,
Byte[] bytes=new byte[10]{‘a’,’b’,’c’}
String str=new String(bytes,1,3)将bytes集合对象的第二和第三个取出来形成字符串对象
或者直接用下面的读取,.为当前目录路径,..为上级目录,/为绝对路径即为根目录skills目录为与src同级的目录:
String orifilePath = FileUtils.getFile("./skills/yw.txt").getAbsolutePath();
File fileOri = new File(orifilePath);
String strOri = FileUtils.readFileToString(file2);
读取xlsx(excel)时可以将excel复制到txt文件中然后用FileUtils获取里面的内容。
String orifilePath = FileUtils.getFile("./skills/yw.txt").getAbsolutePath();
File fileOri = new File(orifilePath);
//FileUtils为apache.commons.io包中的类
String strOri = FileUtils.readFileToString(fileOri);
String[] split2 = strOri.split("\n");// 换行
for(String s:split2){
JSONArray itemArr = new JSONArray();
s=s.replaceAll("\\r", "");
String[] split3 = s.split("\t"); //获取到单个列
itemArr.add(split3[0]);
itemArr.add(Arrays.stream(split3).collect(Collectors.joining(",")));
contentArr.add(itemArr);//将每一列放到jsonArray中。
}
本文介绍了如何在不同操作系统上高效地读取文件内容的方法,包括使用Spring框架下的Resource类和IOUtils工具类来处理文件读取问题,并展示了如何解析CSV文件及Excel表格。
228

被折叠的 条评论
为什么被折叠?



