Java 7 引入了 NIO.21,其中包含声明方法 readAllLines2 的类 java.nio.Files。由于您声明您的文件最多可以包含 100 行,因此方法 readAllLines 似乎是合适的。然后你需要做的就是指出你想要的行[s]的索引[es]。下面的代码演示。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class FileLine {
public static void showLines(List<String> lines, int first, int last) {
if (lines != null && first >= 0 && last < lines.size() && first <= last) {
for (int i = first; i <= last; i++) {
System.out.println(lines.get(i));
}
}
}
public static void main(String[] args) {
Path path = Paths.get("t.txt");
try {
List<String> lines = Files.readAllLines(path); // throws java.io.IOException
showLines(lines, 2, 2);
System.out.println("================================================================");
showLines(lines, 5, 14);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
请注意,List 中第一行的索引为 0(零)。
我运行上述代码时的输出是:
Boys will be boys
================================================================
Hour to hour
Sorry, not sorry
Over and over
Home sweet home
Smile, smile, smile at your mind as often as possible.
Alone, alone at last
Now you see me; now you don’t
Rain, rain go away
All for one and one for all
It is what it is
或者,如果您想将某些文件行收集到一个单独的列表中,请考虑以下代码(与上述代码略有不同)。
public class FileLine {
public static List<String> getLines(List<String> lines, int first, int last) {
List<String> list = new ArrayList<>();
if (lines != null && first >= 0 && last < lines.size() && first <= last) {
for (int i = first; i <= last; i++) {
list.add(lines.get(i));
}
}
return list;
}
public static void main(String[] args) {
Path path = Paths.get("t.txt");
try {
List<String> lines = Files.readAllLines(path);
List<String> selectedLines = getLines(lines, 2, 2);
selectedLines.addAll(getLines(lines, 5, 14));
System.out.println(selectedLines);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
运行替代代码会给出以下输出:
[Boys will be boys, Hour to hour, Sorry, not sorry, Over and over, Home sweet home, Smile, smile, smile at your mind as often as possible., Alone, alone at last, Now you see me; now you don’t, Rain, rain go away, All for one and one for all, It is what it is]
1 NIO 是在 Java 1.4 中引入的
2 确切地说,该方法是在 Java 8 中添加的。在 Java 7 中,您还必须指出
2 em>charset 文件。