-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStreamOfLines.java
More file actions
65 lines (57 loc) · 1.5 KB
/
StreamOfLines.java
File metadata and controls
65 lines (57 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package StreamExamples;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamOfLines
{
public static void main(String[] args)
{
//Read file line by line
Path filePath1 = Paths.get("C:\\temp", "data.txt");
try(Stream<String> lines = Files.lines(filePath1))
{
lines.forEach(System.out::println);
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println();
//Filtering Stream of Lines
Path filePath2 = Paths.get("c:/temp", "data.txt");
try
{
Files.lines(filePath2).filter(s -> s.contains("How are you"))
.collect(Collectors.toList()).forEach(System.out::println);
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println();
//Reading file using FileReader
try
{
File file = new File("c:/temp/data.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null)
{
if(line.contains("How are you"))
{
System.out.println(line);
}
}
br.close();
fr.close();
}
catch(Exception e){System.out.print(e);}
}
}