Reputation: 13
I have a java file reader method. The file consist of many line ( upt 100 lines). I was interested to read and store Line 2 and as well as line 5 - 15 while am storing them into an arrayList. The issue am having is, I dunno how to get the content of a specific line For example : this is the file content.
Time after time
Heart to heart
Boys will be boys
Hand in hand
Get ready; get set; go
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
Java API that am using is
File f = new File ("t.txt");
and
BufferedReader br = new BufferedReader(new FileReader(f))
Upvotes: 0
Views: 1127
Reputation: 3718
get line(s) by their respective line-number with lambda
Set<Integer> linesToGet = Set.of(2, 5, 15);
try(Stream<String> stream = Files.lines(Paths.get("test.txt"))) {
int[] line = {1};
List<String> list = stream.filter(s -> linesToGet.contains(line[0]++))
.collect(toList());
}
catch (IOException ex) {…}
gets: [Heart to heart, Get ready; get set; go, It is what it is]
Upvotes: 0
Reputation: 20914
Java 7 introduced NIO.21 which includes class java.nio.Files
which declares method readAllLines2. Since you state that your file may contain a maximum of 100 lines, method readAllLines
seems appropriate. Then all you need to do is indicate the index[es] of the line[s] you want. The below code demonstrates.
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();
}
}
}
Note that the index of the first line in the List
is 0 (zero).
The output when I run the above code is:
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
Alternatively, if you want to collect certain file lines into a separate list, then consider the following code (which is slightly changed from the above code).
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();
}
}
}
Running the alternative code gives the following output:
[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 was introduced in Java 1.4
2 To be precise, that method was added in Java 8. In Java 7 you also had to indicate the charset of the file.
Upvotes: 0
Reputation: 5294
Extract the logic you need into a method looking at the general case.
Given a file f
, read only a subset of lines. One way of looking at this is with a method like
List<String> readLines(File f, Function<Integer, Boolean> check);
You could define such a method as follows:
List<String> readLines(File f, Function<Integer, Boolean> check) throws IOException {
List<String> list = new ArrayList<>();
int count = 0;
String line;
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
while((line = br.readLine()) != null) {
count++;
if (check.apply(count)) {
list.add(line);
}
}
}
return list;
}
Defining the check function as appropriate whereby given an integer it will return true / false if the line is to be added, you can generalize for different use cases.
For exmaple (in your case), the check function would be
Function<Integer, Boolean> check = lineNumber -> lineNumber == 2 || (lineNumber >= 5 && lineNumber <= 15);
Upvotes: 0
Reputation: 883
Files are read through streams and each line is accessed sequentially, not randomly. One way to handle this is to have a counter that you check inside a loop, something like:
int count = 1; // line counter
String line; // current line being read
while((line = br.readLine()) != null) {
if(count == 2 ||
(count >= 5 && count <= 15))
arrayList.add(line);
count++;
}
Upvotes: 1