SlideShare a Scribd company logo
1 of 53
Using Streams, Files, Serialization
Files and Streams
Software University
http://softuni.bg
SoftUni Team
Technical Trainers
1
Table of Content
1. Streams Basics
 Opening a File Stream
 Closing a File Stream
2. Types of Streams
 Combining Streams
3. Files and Directories
4. Serialization
2
sli.do
#java-advanced
Have a Question?
3
Streams
Opening and Closing Streams
5
What is Stream?
 Streams are used to transfer data
 We open a stream to:
 Read a file
 Write to a file
Stream
1100 1001 1001
6
 Two fundamental types of streams:
Streams Basics
Input Stream
1100 1001 1001
Output Stream
1100 1001 1001
Streams are
unidirectional!
7
Opening a File Stream
String path = "C:input.txt";
FileInputStream fileStream =
new FileInputStream(path);
int oneByte = fileStream.read();
while (oneByte >= 0) {
System.out.print(oneByte);
oneByte = fileStream.read();
}
Returns -1 if
empty
8
 Using try-catch-finally
InputStream in = null;
try {
in = new FileInputStream(path);
} catch (IOException e) {
// TODO: handle exception
} finally {
if (in != null) {
in.close();
}
}
Closing a File Stream (1)
Always free
resources!
close() can also
throw an exception
9
 Using try-with-resources
try (InputStream in = new FileInputStream(path)) {
int oneByte = in.read();
while (oneByte >= 0) {
System.out.print(oneByte);
oneByte = in.read();
}
} catch (IOException e) {
// TODO: handle exception
}
Closing a File Stream (2)
Problem: Read File
10
 You are given a file
 Read and print all of its contents as a sequence of bytes
 Submit in Judge only the output of the program
Two households, both
alike in dignity,
In fair Verona, where we
lay our scene,
1010100 1110111 1101111
100000 1101000 1101111
1110101 1110011 1100101
1101000…
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
Solution: Read File
11
String path = "D:input.txt";
try (InputStream in = new FileInputStream(path)) {
int oneByte = in.read();
while (oneByte >= 0) {
System.out.printf("%s ",
Integer.toBinaryString(oneByte));
oneByte = in.read();
}
}
catch (IOException e) {
e.printStackTrace();
}
Problem: Write to File
12
 Read a file and write all its content while skipping any
punctuation (skip ',', '.', '!', '?')
 Submit in Judge only the output of the program
Two households, both
alike in dignity.
In fair Verona, where
we lay our scene.
Two households both
alike in dignity
In fair Verona where
we lay our scene
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
Solution: Write to File (1)
13
String inputPath = "D:input.txt";
String outputPath = "D:output.txt";
List<Character> symbols = new ArrayList<>();
Collections.addAll(symbols, '.', ',', '!', '?');
// continues…
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
Solution: Write to File (2)
14
try (InputStream in = new FileInputStream(inputPath);
OutputStream out = new FileOutputStream(outputPath))
{
int oneByte = 0;
while ((oneByte = in.read()) >= 0) {
if (!symbols.contains((char)oneByte)) {
out.write(oneByte);
}
}
} // TODO: handle exceptions
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
Basic Stream Types in Java
Byte and Character
16
 Byte streams are the lowest level streams
 Byte streams can read or write one byte at a time
 All byte streams descend from InputStream and OutputStream
Byte Stream
InputStream
OutputStream
100101 111111 100011 -1
100101 111111 100011
17
 Read a file and copy its contents to another text file
 Write characters as bytes in decimal
 Write every space or new line as it is, e.g. as a
space or new line
Problem: Copy Bytes
Two households, both
alike in dignity.
In fair Verona, where
we lay our scene.
84119111
10411111711510110411…
73110 10297105114
861011141111109744 1…
T w o space
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
18
Solution: Copy Bytes
// TODO: Open input and output streams
int oneByte = 0;
while ((oneByte = in.read()) >= 0) {
if (oneByte == 10 || oneByte == 32) {
out.write(oneByte);
} else {
String digits = String.valueOf(oneByte);
for (int i = 0; i < digits.length(); i++)
out.write(digits.charAt(i));
}
} // TODO: handle exceptions
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
19
 All character streams descend from
FileReader and FileWriter
Character Streams
String path = "D:input.txt";
FileReader reader = new FileReader(path);
20
 Character streams are often "wrappers" for byte streams
 FileReader uses FileInputStream
 FileWriter uses FileOutputStream
Combining Streams
String path = "D:input.txt";
Scanner reader =
new Scanner(new FileInputStream(path));
Wrapping a
Stream
21
 Read a file and extracts all integers in a separate file
 Get only numbers that are not a part of a word
 Submit in Judge only the output of the program
Problem: Extract Integers
2 households, 22 alike
in 3nity,
In fair Verona, where
we lay our scene
2
22
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
22
Solution: Extract Integers
Scanner scanner =
new Scanner(new FileInputStream(inputPath));
PrintWriter out =
new PrintWriter(new FileOutputStream(outputPath));
while (scanner.hasNext()) {
if (scanner.hasNextInt())
out.println(scanner.nextInt());
scanner.next();
}
out.close();
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
Buffered Streams
23
 Reading information in chunks
 Significantly boost performance
F i l e s a n d
46 69 6c 65 73 20 61 6e 64
Position
46 69Buffer 6c 65 73 20 61 6e 64
Length = 9
Problem: Write Every Third Line
24
 Read a file and write all lines which number is divisible by 3
in a separate file
 Line numbers start from one
Two households, both
alike in dignity,
In fair Verona, where
we lay our scene,
From ancient grudge
break to new mutiny…
10101
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
Solution: Write Every Third Line
25
try (BufferedReader in =
new BufferedReader(new FileReader(inputPath));
PrintWriter out =
new PrintWriter(new FileWriter(outputPath))) {
int counter = 1;
String line = in.readLine();
while (line != null) {
if (counter % 3 == 0)
out.println(line);
counter++;
line = in.readLine();
}
} // TODO: handle exceptions
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
26
 Standard Input - System.in
 Standard Output - System.out
 Standard Error - System.err
Command Line I/O (1)
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
System.out.println(line);
Input Stream
Output Stream
27
Command Line I/O (2)
public static void main(String[] args) throws IOException {
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
String hello = reader.readLine(); // Hello BufferedReader
System.out.println(hello); // Hello BufferedReader
}
Files and Paths
Easily Working With Files
29
 The location of a file in the file system
 Represented in Java by the Path class
Paths
D:input.txt
Path path = Paths.get("D:input.txt");
input.txt other files
D:Root folder
30
 Provides static methods for creating streams
Files (1)
Path path = Paths.get("D:input.txt");
try (BufferedReader reader =
Files.newBufferedReader(path)) {
// TODO: work with file
} catch (IOException e) {
// TODO: handle exception
}
31
 Provides utility methods for easy file manipulation
Files (2)
Path inPath = Paths.get("D:input.txt");
Path outPath = Paths.get("D:output.txt");
List<String> lines = Files.readAllLines(inPath);
Files.write(outPath, lines);
// TODO: handle exceptions
32
 Read a text file and sort all lines
 Write the result to another text file
 Use Paths and Files classes
Problem: Sort Lines
C
A
B
D
…
A
B
C
D
…
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
33
Solution: Sort Lines
Path path = Paths.get("D:input.txt");
Path output = Paths.get("D:output.txt");
try {
List<String> lines = Files.readAllLines(path);
lines = lines.stream().filter(l ->
!l.isBlank()).collect(Collectors.toList());
Collections.sort(lines);
Files.write(output, lines);
} catch (IOException e) {
e.printStackTrace();
}
Don't use for large files
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
File Class in Java
Easily Working With Files
35
import java.io.File;
File file = new File("D:input.txt");
boolean isExisting = file.exists();
long length = file.length();
boolean isDirectory = file.isDirectory();
File[] files = file.listFiles();
 Provides methods for quick and easy manipulation of files
File Class in Java
36
 Print names and sizes of all files in
"Files-and-Streams" directory
 Skip child directories
Problem: List Files
input.txt: [size in bytes]
output.txt: [size in bytes]
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
37
Solution: List Files
if (file.exists()) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
if (!f.isDirectory()) {
System.out.printf("%s: [%s]%n",
f.getName(), f.length());
}
}
}
}
38
 You are given a folder named "Files-and-Streams"
 List all folder names, starting with the root
 Print folder count on the last line (including the root)
Problem: Nested Folders
…
Streams-and-Files
Serialization
Streams-and-Files
[count] folders
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
39
Solution: Nested Folders (1)
String path = "D:Files-and-Streams";
File root = new File(path);
Deque<File> dirs = new ArrayDeque<>();
dirs.offer(root);
// continue…
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
40
Solution: Nested Folders (2)
int count = 0;
while (!dirs.isEmpty()) {
File current = dirs.poll();
File[] nestedFiles = current.listFiles();
for (File nestedFile : nestedFiles)
if (nestedFile.isDirectory())
dirs.offer(nestedFile);
count++;
System.out.println(current.getName());
}
System.out.println(count + " folders");
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
Serialization
Serializing and Deserializing Objects
42
 Save objects to a file
Serialization
List<String> names = new ArrayList<>();
Collections.addAll(names, "Mimi", "Gosho");
FileOutputStream fos = new FileOutputStream(path);
ObjectOutputStream oos =
new ObjectOutputStream(fos);
oos.writeObject(names);
// TODO: handle exceptions
Save objects
to .ser file
43
 Load objects from a file
Deserialization
FileInputStream fis =
new FileInputStream(path);
ObjectInputStream oos =
new ObjectInputStream(fis);
List<String> names =
(List<String>) oos.readObject();
// TODO: handle exceptions
44
 Custom objects should implement the Serializable interface
Serialization of Custom Objects
class Cube implements Serializable {
String color;
double width;
double height;
double depth;
}
45
 Create a Cube class with color, width, height and depth
 Create a cube – color: "green", w: 15.3, h: 12.4 and d: 3
Problem: Serialize Custom Object
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
Solution: Serialize Custom Object (1)
46
class Cube implements Serializable {
String color;
double width;
double height;
double depth;
}
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
Solution: Serialize Custom Object (2)
47
//TODO: Create Cube object
String path = "D:save.ser";
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(path))) {
oos.writeObject(cube);
} catch (IOException e) {
e.printStackTrace();
}
Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
 …
 …
 …
Summary
48
 Streams are used to transfer data
 Two main types of streams
 Input Streams
 Output Streams
 Buffered streams boost performance
 Streams can be chained together
 You can save objects state into a file
 https://softuni.bg/modules/59/java-advanced
SoftUni Diamond Partners
SoftUni Organizational Partners
 Software University – High-Quality Education and
Employment Opportunities
 softuni.bg
 Software University Foundation
 http://softuni.foundation/
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg
Trainings @ Software University (SoftUni)
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-NonCom
mercial-ShareAlike 4.0 International" license
License
53

More Related Content

More from Intro C# Book

19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexityIntro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classesIntro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and MapsIntro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with javaIntro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem SolvingIntro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQIntro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming CodeIntro C# Book
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm ComplexityIntro C# Book
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and SetIntro C# Book
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like StructuresIntro C# Book
 

More from Intro C# Book (20)

19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 

Recently uploaded

Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With RoomVIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Roomdivyansh0kumar0
 
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kestopur 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Roomdivyansh0kumar0
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
Gram Darshan PPT cyber rural in villages of india
Gram Darshan PPT cyber rural  in villages of indiaGram Darshan PPT cyber rural  in villages of india
Gram Darshan PPT cyber rural in villages of indiaimessage0108
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With RoomVIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Roomgirls4nights
 
Denver Web Design brochure for public viewing
Denver Web Design brochure for public viewingDenver Web Design brochure for public viewing
Denver Web Design brochure for public viewingbigorange77
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...akbard9823
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...aditipandeya
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)Damian Radcliffe
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsThierry TROUIN ☁
 
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 

Recently uploaded (20)

Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girls
 
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICECall Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With RoomVIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Room
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kestopur 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
Gram Darshan PPT cyber rural in villages of india
Gram Darshan PPT cyber rural  in villages of indiaGram Darshan PPT cyber rural  in villages of india
Gram Darshan PPT cyber rural in villages of india
 
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With RoomVIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
 
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance VVIP 🍎 SERVICE
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SERVICECall Girls Service Dwarka @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SERVICE
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance VVIP 🍎 SERVICE
 
Denver Web Design brochure for public viewing
Denver Web Design brochure for public viewingDenver Web Design brochure for public viewing
Denver Web Design brochure for public viewing
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
 
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
Sushant Golf City / best call girls in Lucknow | Service-oriented sexy call g...
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with Flows
 
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
 

15. Java streams files and directories

  • 1. Using Streams, Files, Serialization Files and Streams Software University http://softuni.bg SoftUni Team Technical Trainers 1
  • 2. Table of Content 1. Streams Basics  Opening a File Stream  Closing a File Stream 2. Types of Streams  Combining Streams 3. Files and Directories 4. Serialization 2
  • 5. 5 What is Stream?  Streams are used to transfer data  We open a stream to:  Read a file  Write to a file Stream 1100 1001 1001
  • 6. 6  Two fundamental types of streams: Streams Basics Input Stream 1100 1001 1001 Output Stream 1100 1001 1001 Streams are unidirectional!
  • 7. 7 Opening a File Stream String path = "C:input.txt"; FileInputStream fileStream = new FileInputStream(path); int oneByte = fileStream.read(); while (oneByte >= 0) { System.out.print(oneByte); oneByte = fileStream.read(); } Returns -1 if empty
  • 8. 8  Using try-catch-finally InputStream in = null; try { in = new FileInputStream(path); } catch (IOException e) { // TODO: handle exception } finally { if (in != null) { in.close(); } } Closing a File Stream (1) Always free resources! close() can also throw an exception
  • 9. 9  Using try-with-resources try (InputStream in = new FileInputStream(path)) { int oneByte = in.read(); while (oneByte >= 0) { System.out.print(oneByte); oneByte = in.read(); } } catch (IOException e) { // TODO: handle exception } Closing a File Stream (2)
  • 10. Problem: Read File 10  You are given a file  Read and print all of its contents as a sequence of bytes  Submit in Judge only the output of the program Two households, both alike in dignity, In fair Verona, where we lay our scene, 1010100 1110111 1101111 100000 1101000 1101111 1110101 1110011 1100101 1101000… Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 11. Solution: Read File 11 String path = "D:input.txt"; try (InputStream in = new FileInputStream(path)) { int oneByte = in.read(); while (oneByte >= 0) { System.out.printf("%s ", Integer.toBinaryString(oneByte)); oneByte = in.read(); } } catch (IOException e) { e.printStackTrace(); }
  • 12. Problem: Write to File 12  Read a file and write all its content while skipping any punctuation (skip ',', '.', '!', '?')  Submit in Judge only the output of the program Two households, both alike in dignity. In fair Verona, where we lay our scene. Two households both alike in dignity In fair Verona where we lay our scene Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 13. Solution: Write to File (1) 13 String inputPath = "D:input.txt"; String outputPath = "D:output.txt"; List<Character> symbols = new ArrayList<>(); Collections.addAll(symbols, '.', ',', '!', '?'); // continues… Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 14. Solution: Write to File (2) 14 try (InputStream in = new FileInputStream(inputPath); OutputStream out = new FileOutputStream(outputPath)) { int oneByte = 0; while ((oneByte = in.read()) >= 0) { if (!symbols.contains((char)oneByte)) { out.write(oneByte); } } } // TODO: handle exceptions Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 15. Basic Stream Types in Java Byte and Character
  • 16. 16  Byte streams are the lowest level streams  Byte streams can read or write one byte at a time  All byte streams descend from InputStream and OutputStream Byte Stream InputStream OutputStream 100101 111111 100011 -1 100101 111111 100011
  • 17. 17  Read a file and copy its contents to another text file  Write characters as bytes in decimal  Write every space or new line as it is, e.g. as a space or new line Problem: Copy Bytes Two households, both alike in dignity. In fair Verona, where we lay our scene. 84119111 10411111711510110411… 73110 10297105114 861011141111109744 1… T w o space Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 18. 18 Solution: Copy Bytes // TODO: Open input and output streams int oneByte = 0; while ((oneByte = in.read()) >= 0) { if (oneByte == 10 || oneByte == 32) { out.write(oneByte); } else { String digits = String.valueOf(oneByte); for (int i = 0; i < digits.length(); i++) out.write(digits.charAt(i)); } } // TODO: handle exceptions Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 19. 19  All character streams descend from FileReader and FileWriter Character Streams String path = "D:input.txt"; FileReader reader = new FileReader(path);
  • 20. 20  Character streams are often "wrappers" for byte streams  FileReader uses FileInputStream  FileWriter uses FileOutputStream Combining Streams String path = "D:input.txt"; Scanner reader = new Scanner(new FileInputStream(path)); Wrapping a Stream
  • 21. 21  Read a file and extracts all integers in a separate file  Get only numbers that are not a part of a word  Submit in Judge only the output of the program Problem: Extract Integers 2 households, 22 alike in 3nity, In fair Verona, where we lay our scene 2 22 Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 22. 22 Solution: Extract Integers Scanner scanner = new Scanner(new FileInputStream(inputPath)); PrintWriter out = new PrintWriter(new FileOutputStream(outputPath)); while (scanner.hasNext()) { if (scanner.hasNextInt()) out.println(scanner.nextInt()); scanner.next(); } out.close(); Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 23. Buffered Streams 23  Reading information in chunks  Significantly boost performance F i l e s a n d 46 69 6c 65 73 20 61 6e 64 Position 46 69Buffer 6c 65 73 20 61 6e 64 Length = 9
  • 24. Problem: Write Every Third Line 24  Read a file and write all lines which number is divisible by 3 in a separate file  Line numbers start from one Two households, both alike in dignity, In fair Verona, where we lay our scene, From ancient grudge break to new mutiny… 10101 Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 25. Solution: Write Every Third Line 25 try (BufferedReader in = new BufferedReader(new FileReader(inputPath)); PrintWriter out = new PrintWriter(new FileWriter(outputPath))) { int counter = 1; String line = in.readLine(); while (line != null) { if (counter % 3 == 0) out.println(line); counter++; line = in.readLine(); } } // TODO: handle exceptions Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 26. 26  Standard Input - System.in  Standard Output - System.out  Standard Error - System.err Command Line I/O (1) Scanner scanner = new Scanner(System.in); String line = scanner.nextLine(); System.out.println(line); Input Stream Output Stream
  • 27. 27 Command Line I/O (2) public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String hello = reader.readLine(); // Hello BufferedReader System.out.println(hello); // Hello BufferedReader }
  • 28. Files and Paths Easily Working With Files
  • 29. 29  The location of a file in the file system  Represented in Java by the Path class Paths D:input.txt Path path = Paths.get("D:input.txt"); input.txt other files D:Root folder
  • 30. 30  Provides static methods for creating streams Files (1) Path path = Paths.get("D:input.txt"); try (BufferedReader reader = Files.newBufferedReader(path)) { // TODO: work with file } catch (IOException e) { // TODO: handle exception }
  • 31. 31  Provides utility methods for easy file manipulation Files (2) Path inPath = Paths.get("D:input.txt"); Path outPath = Paths.get("D:output.txt"); List<String> lines = Files.readAllLines(inPath); Files.write(outPath, lines); // TODO: handle exceptions
  • 32. 32  Read a text file and sort all lines  Write the result to another text file  Use Paths and Files classes Problem: Sort Lines C A B D … A B C D … Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 33. 33 Solution: Sort Lines Path path = Paths.get("D:input.txt"); Path output = Paths.get("D:output.txt"); try { List<String> lines = Files.readAllLines(path); lines = lines.stream().filter(l -> !l.isBlank()).collect(Collectors.toList()); Collections.sort(lines); Files.write(output, lines); } catch (IOException e) { e.printStackTrace(); } Don't use for large files Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 34. File Class in Java Easily Working With Files
  • 35. 35 import java.io.File; File file = new File("D:input.txt"); boolean isExisting = file.exists(); long length = file.length(); boolean isDirectory = file.isDirectory(); File[] files = file.listFiles();  Provides methods for quick and easy manipulation of files File Class in Java
  • 36. 36  Print names and sizes of all files in "Files-and-Streams" directory  Skip child directories Problem: List Files input.txt: [size in bytes] output.txt: [size in bytes] Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 37. 37 Solution: List Files if (file.exists()) { if (file.isDirectory()) { File[] files = file.listFiles(); for (File f : files) { if (!f.isDirectory()) { System.out.printf("%s: [%s]%n", f.getName(), f.length()); } } } }
  • 38. 38  You are given a folder named "Files-and-Streams"  List all folder names, starting with the root  Print folder count on the last line (including the root) Problem: Nested Folders … Streams-and-Files Serialization Streams-and-Files [count] folders Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 39. 39 Solution: Nested Folders (1) String path = "D:Files-and-Streams"; File root = new File(path); Deque<File> dirs = new ArrayDeque<>(); dirs.offer(root); // continue… Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 40. 40 Solution: Nested Folders (2) int count = 0; while (!dirs.isEmpty()) { File current = dirs.poll(); File[] nestedFiles = current.listFiles(); for (File nestedFile : nestedFiles) if (nestedFile.isDirectory()) dirs.offer(nestedFile); count++; System.out.println(current.getName()); } System.out.println(count + " folders"); Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 42. 42  Save objects to a file Serialization List<String> names = new ArrayList<>(); Collections.addAll(names, "Mimi", "Gosho"); FileOutputStream fos = new FileOutputStream(path); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(names); // TODO: handle exceptions Save objects to .ser file
  • 43. 43  Load objects from a file Deserialization FileInputStream fis = new FileInputStream(path); ObjectInputStream oos = new ObjectInputStream(fis); List<String> names = (List<String>) oos.readObject(); // TODO: handle exceptions
  • 44. 44  Custom objects should implement the Serializable interface Serialization of Custom Objects class Cube implements Serializable { String color; double width; double height; double depth; }
  • 45. 45  Create a Cube class with color, width, height and depth  Create a cube – color: "green", w: 15.3, h: 12.4 and d: 3 Problem: Serialize Custom Object Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 46. Solution: Serialize Custom Object (1) 46 class Cube implements Serializable { String color; double width; double height; double depth; } Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 47. Solution: Serialize Custom Object (2) 47 //TODO: Create Cube object String path = "D:save.ser"; try (ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(path))) { oos.writeObject(cube); } catch (IOException e) { e.printStackTrace(); } Check your solution here: https://judge.softuni.bg/Contests/1493/Streams-Files-And-Directories-Lab
  • 48.  …  …  … Summary 48  Streams are used to transfer data  Two main types of streams  Input Streams  Output Streams  Buffered streams boost performance  Streams can be chained together  You can save objects state into a file
  • 52.  Software University – High-Quality Education and Employment Opportunities  softuni.bg  Software University Foundation  http://softuni.foundation/  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums  forum.softuni.bg Trainings @ Software University (SoftUni)
  • 53.  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution-NonCom mercial-ShareAlike 4.0 International" license License 53