3 回答
TA贡献1900条经验 获得超5个赞
假设您的代码工作正常:
public static List<String> readFile(int n) throws IOException {
try(BufferedReader br = new BufferedReader(new
FileReader("C:\\\\\\\\Users\\\\\\\\Admin\\\\\\\\Desktop\\\\\\\\Work Files\\\\\\\\314-
WO0000001133814\\\\\\\\Cards\\\\\\\\MBD10760_182.out"))){
List<String> listOfData = new ArrayList<>();
String d;
while((d = br.readLine()) != null && n>0){
listOfData.add(d);
n--;
}
return listOfData;
}
只是你必须告诉循环它应该读多少行。如果文件少于 n 行,则 while 循环的第一条语句将返回 null 并中断循环。否则,当它读取 n 行时,由于 while 循环中的第二条语句,它将再次中断循环
TA贡献1757条经验 获得超7个赞
只需在检查 listOfData 大小时添加:
while( ((d = br.readLine()) != null) && listOfData.size()<20 ) {
listOfData.add(d);
}
TA贡献1776条经验 获得超12个赞
public static void main(String[] args) throws IOException {
Path pathFrom = Paths.get("C:\\Users\\Admin\\Desktop\\Work Files\\314-WO0000001133814\\Cards\\MBD10760_182.out\"");
Path pathTo = Paths.get("C:\\Users\\Admin\\Desktop\\Work Files\\314-WO0000001133814\\Cards\\MBD10760_187.out\"");
Files.write(pathTo, Files.lines(pathFrom).limit(20).collect(Collectors.toList()));
}
添加回答
举报