Min*_*mut 1 java text-files filereader
所以,我需要逐行读取文本文件,并按字符串返回它们.我可以指定从哪行到哪一行我想读它.
我的班有3种方法:
public class FilePartReader {
String filePath;
Integer fromLine;
Integer toLine;
public FilePartReader() { }
public void setup(String filepath, Integer fromLine, Integer toLine) {
if (fromLine < 0 || toLine <= fromLine) {
throw new IllegalArgumentException(
"fromline cant be smaller than 0 and toline cant be smaller than fromline");
}
this.filePath = filepath;
this.fromLine = fromLine;
this.toLine = toLine;
}
public String read() throws IOException {
String data;
data = new String(Files.readAllBytes(Paths.get(filePath)));
return data;
}
public String readLines() {
return "todo";
}
}
Run Code Online (Sandbox Code Playgroud)
read()方法应该打开文件路径,并将内容作为字符串返回.readLines()应该使用read()读取文件并从fromLine和toLine之间的内容中返回每一行(包括它们两者),并将这些行作为String返回.现在,我不确定read()是否正确实现,因为如果我理解正确将整个内容作为一个大字符串返回,也许有更好的解决方案吗?另外,我如何使fromLine/toLine工作?提前致谢
您可以使用Files.lines它返回Stream<String>的所有生产线和应用skip,并limit以结果流:
Stream<String> stream = Files.lines(Paths.get(fileName))
.skip(fromLine)
.limit(toLine - fromLine);
Run Code Online (Sandbox Code Playgroud)
这将为您提供Stream从一开始到fromLine结束的一行toLine.之后,您可以将其转换为数据结构(例如列表)或执行任何需要完成的操作.
| 归档时间: |
|
| 查看次数: |
344 次 |
| 最近记录: |