-
Notifications
You must be signed in to change notification settings - Fork 137
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add I/O Streams & Files code snippets
- Loading branch information
Showing
11 changed files
with
629 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
# Входно-изходни потоци и файлове |
115 changes: 115 additions & 0 deletions
115
07-io-streams-and-files/snippets/src/bg/sofia/uni/fmi/mjt/io/CipherExample.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
package bg.sofia.uni.fmi.mjt.io; | ||
|
||
import java.io.FileInputStream; | ||
import java.io.FileOutputStream; | ||
import java.io.IOException; | ||
import java.io.InputStream; | ||
import java.io.OutputStream; | ||
import java.nio.charset.StandardCharsets; | ||
import java.nio.file.Files; | ||
import java.nio.file.Path; | ||
import java.nio.file.StandardOpenOption; | ||
import java.nio.file.attribute.PosixFilePermissions; | ||
import java.security.NoSuchAlgorithmException; | ||
import java.util.Base64; | ||
import java.util.List; | ||
|
||
import javax.crypto.Cipher; | ||
import javax.crypto.CipherOutputStream; | ||
import javax.crypto.KeyGenerator; | ||
import javax.crypto.SecretKey; | ||
import javax.crypto.spec.SecretKeySpec; | ||
|
||
public class CipherExample { | ||
|
||
private static final int KILOBYTE = 1024; | ||
private static final String ENCRYPTION_ALGORITHM = "AES"; // // Advanced Encryption Standard | ||
private static final String KEY_FILE_PATH = "secret.key"; | ||
private static final int KEY_SIZE_IN_BITS = 128; // Key sizes like 192 or 256 might not be available on all systems | ||
|
||
public static void main(String[] args) { | ||
try { | ||
// Generate | ||
SecretKey secretKey = generateSecretKey(); | ||
|
||
// uncomment to store the key in file | ||
//persistSecretKey(secretKey); | ||
|
||
// uncomment to load the key from file | ||
//secretKey = loadSecretKey(); | ||
|
||
// Encrypt | ||
encryptData(secretKey); | ||
|
||
// Decrypt | ||
decryptData(secretKey); | ||
|
||
} catch (Exception e) { | ||
throw new RuntimeException("Exception caught during the execution", e); | ||
} | ||
} | ||
|
||
private static SecretKey generateSecretKey() throws NoSuchAlgorithmException { | ||
KeyGenerator keyGenerator = KeyGenerator.getInstance(ENCRYPTION_ALGORITHM); | ||
keyGenerator.init(KEY_SIZE_IN_BITS); | ||
SecretKey secretKey = keyGenerator.generateKey(); | ||
|
||
// In order to view the key in some text representation, we'll convert it to Base64 format | ||
// Comment the next two lines if that's not needed | ||
String base64Key = Base64.getEncoder().encodeToString(secretKey.getEncoded()); | ||
System.out.println("Generated Secret Key (Base64-encoded): " + base64Key); | ||
|
||
return secretKey; | ||
} | ||
|
||
private static void persistSecretKey(SecretKey secretKey) throws IOException { | ||
byte[] keyBytes = secretKey.getEncoded(); | ||
Path keyFilePath = Path.of(KEY_FILE_PATH); | ||
|
||
// Write key bytes to file | ||
Files.write(keyFilePath, keyBytes, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); | ||
|
||
// (Optional) Set file permissions to restrict access | ||
Files.setPosixFilePermissions(keyFilePath, PosixFilePermissions.fromString("rw-------")); | ||
} | ||
|
||
private static SecretKey loadSecretKey() throws IOException { | ||
byte[] keyBytes = Files.readAllBytes(Path.of(KEY_FILE_PATH)); | ||
return new SecretKeySpec(keyBytes, ENCRYPTION_ALGORITHM); | ||
} | ||
|
||
private static void encryptData(SecretKey secretKey) throws Exception { | ||
Cipher cipher = Cipher.getInstance("AES"); | ||
cipher.init(Cipher.ENCRYPT_MODE, secretKey); | ||
|
||
try (var outputStream = new CipherOutputStream(new FileOutputStream("encryptedText.txt"), cipher)) { | ||
List<String> data = List.of("my-", "secret-", "pass–", "and–", "other–", "stuff"); | ||
|
||
for (String str : data) { | ||
byte[] dataBytes = str.getBytes(StandardCharsets.UTF_8); | ||
outputStream.write(dataBytes); | ||
} | ||
|
||
System.out.println("Encryption complete."); | ||
} | ||
} | ||
|
||
private static void decryptData(SecretKey secretKey) throws Exception { | ||
Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM); | ||
cipher.init(Cipher.DECRYPT_MODE, secretKey); | ||
|
||
try (InputStream encryptedInputStream = new FileInputStream("encryptedText.txt"); | ||
OutputStream decryptedOutputStream = new CipherOutputStream(new FileOutputStream("decryptedText.txt"), | ||
cipher)) { | ||
|
||
byte[] buffer = new byte[KILOBYTE]; | ||
int bytesRead; | ||
|
||
while ((bytesRead = encryptedInputStream.read(buffer)) != -1) { | ||
decryptedOutputStream.write(buffer, 0, bytesRead); | ||
} | ||
|
||
System.out.println("Decryption complete."); | ||
} | ||
} | ||
} |
45 changes: 45 additions & 0 deletions
45
07-io-streams-and-files/snippets/src/bg/sofia/uni/fmi/mjt/io/DataStreamExample.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package bg.sofia.uni.fmi.mjt.io; | ||
|
||
import java.io.DataInputStream; | ||
import java.io.DataOutputStream; | ||
import java.io.FileInputStream; | ||
import java.io.FileOutputStream; | ||
import java.io.IOException; | ||
|
||
public class DataStreamExample { | ||
|
||
public static void main(String... args) { | ||
writeWithDataStream(); | ||
readDataStream(); | ||
} | ||
|
||
/** | ||
* Writes structured data using DataOutputStream | ||
* https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/io/DataOutputStream.html | ||
*/ | ||
private static void writeWithDataStream() { | ||
try (var dataOutputStream = new DataOutputStream(new FileOutputStream("test.dat"))) { | ||
dataOutputStream.writeInt(16); | ||
dataOutputStream.writeFloat(5.2f); | ||
dataOutputStream.writeUTF("utf"); | ||
dataOutputStream.flush(); | ||
} catch (IOException e) { | ||
throw new IllegalStateException("A problem occurred while writing to a file", e); | ||
} | ||
} | ||
|
||
/** | ||
* Reads structured data using DataInputStream | ||
* https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/io/DataInputStream.html | ||
*/ | ||
private static void readDataStream() { | ||
try (var dataInputStream = new DataInputStream(new FileInputStream("test.dat"))) { | ||
System.out.println("int: " + dataInputStream.readInt()); | ||
System.out.println("float: " + dataInputStream.readFloat()); | ||
System.out.println("string: " + dataInputStream.readUTF()); | ||
} catch (IOException e) { | ||
throw new IllegalStateException("A problem occurred while reading from a file", e); | ||
} | ||
} | ||
|
||
} |
38 changes: 38 additions & 0 deletions
38
07-io-streams-and-files/snippets/src/bg/sofia/uni/fmi/mjt/io/DiskSizeEstimator.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package bg.sofia.uni.fmi.mjt.io; | ||
|
||
import java.io.IOException; | ||
import java.nio.file.FileStore; | ||
import java.nio.file.FileSystems; | ||
import java.util.Locale; | ||
|
||
public class DiskSizeEstimator { | ||
|
||
private static final double KILOBYTE = 1024.0; | ||
|
||
public static void main(String[] args) throws IOException { | ||
|
||
// обхождаме всички дялове на файловата система по подразбиране | ||
Iterable<FileStore> partitions = FileSystems.getDefault().getFileStores(); | ||
|
||
for (FileStore fs : partitions) { | ||
long totalSpace = fs.getTotalSpace(); | ||
long unallocatedSpace = fs.getUnallocatedSpace(); | ||
long usableSpace = fs.getUsableSpace(); | ||
|
||
System.out.println("Partition: " + fs.name()); | ||
System.out.println( | ||
String.format(Locale.US, "Total space: %,d bytes (%.2f GB)", totalSpace, toGigabytes(totalSpace))); | ||
System.out.println(String.format(Locale.US, "Unallocated space: %,d bytes (%.2f GB)", unallocatedSpace, | ||
toGigabytes(unallocatedSpace))); | ||
System.out.println( | ||
String.format(Locale.US, "Usable space: %,d bytes (%.2f GB)", usableSpace, toGigabytes(usableSpace))); | ||
System.out.println(); | ||
} | ||
|
||
} | ||
|
||
private static double toGigabytes(long bytes) { | ||
return bytes / (KILOBYTE * KILOBYTE * KILOBYTE); | ||
} | ||
|
||
} |
100 changes: 100 additions & 0 deletions
100
07-io-streams-and-files/snippets/src/bg/sofia/uni/fmi/mjt/io/ExecutionTimeComparator.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
package bg.sofia.uni.fmi.mjt.io; | ||
|
||
import java.io.BufferedReader; | ||
import java.io.IOException; | ||
import java.io.InputStream; | ||
import java.io.UncheckedIOException; | ||
import java.io.Writer; | ||
import java.nio.file.Files; | ||
import java.nio.file.Path; | ||
import java.util.Locale; | ||
|
||
public class ExecutionTimeComparator { | ||
|
||
private static final int MAX_ITERATIONS = 1_000_000; | ||
private static final int BUFFER_SIZE = 8_192; | ||
private static final double MEGABYTE = 1_024.0 * 1_024.0; | ||
|
||
public static void main(String... args) { | ||
System.err.println("Read time comparison results:"); | ||
|
||
Path filePath = Path.of("compareExecutionTime.txt"); | ||
String line = "Hello World"; | ||
|
||
fillFileWithText(filePath, line); | ||
|
||
System.out.println("Single byte read took: " | ||
+ readFromFile(filePath) + " milliseconds"); | ||
System.out.println("BufferedReader read took: " | ||
+ readFromFileWithBufferedReader(filePath) + " milliseconds"); | ||
System.out.println("BufferedInputStream read took: " | ||
+ readFromFileWithBufferedInputStream(filePath) + " milliseconds"); | ||
} | ||
|
||
private static void fillFileWithText(Path file, String line) { | ||
try (Writer fileWriter = Files.newBufferedWriter(file)) { | ||
for (int i = 0; i <= MAX_ITERATIONS; i++) { | ||
fileWriter.write(line); | ||
} | ||
|
||
fileWriter.flush(); | ||
|
||
long writtenBytes = line.getBytes().length * MAX_ITERATIONS; | ||
double writtenMegabytes = writtenBytes / MEGABYTE; | ||
System.out.println(String.format( | ||
Locale.US, "Wrote %,d bytes (%.2f MB) to the file", writtenBytes, writtenMegabytes)); | ||
} catch (IOException e) { | ||
throw new UncheckedIOException("A problem occurred while writing to a file", e); | ||
} | ||
} | ||
|
||
private static long readFromFile(Path file) { | ||
try (InputStream inputStream = Files.newInputStream(file)) { | ||
|
||
long startTime = System.nanoTime(); | ||
int data; | ||
while ((data = inputStream.read()) != -1) { | ||
// Do some processing | ||
} | ||
long endTime = System.nanoTime(); | ||
|
||
return (endTime - startTime) / MAX_ITERATIONS; // milliseconds | ||
} catch (IOException e) { | ||
throw new UncheckedIOException("A problem occurred while reading from a file", e); | ||
} | ||
} | ||
|
||
private static long readFromFileWithBufferedReader(Path file) { | ||
try (BufferedReader bufferedReader = Files.newBufferedReader(file)) { // default buffer size is 8192 chars | ||
|
||
long startTime = System.nanoTime(); | ||
String line; | ||
while ((line = bufferedReader.readLine()) != null) { | ||
// Do some processing | ||
} | ||
long endTime = System.nanoTime(); | ||
|
||
return (endTime - startTime) / MAX_ITERATIONS; | ||
} catch (IOException e) { | ||
throw new UncheckedIOException("A problem occurred while reading from a file", e); | ||
} | ||
} | ||
|
||
private static long readFromFileWithBufferedInputStream(Path file) { | ||
try (InputStream inputStream = Files.newInputStream(file)) { | ||
byte[] buff = new byte[BUFFER_SIZE]; // 8 KB buffer | ||
int r = 0; | ||
|
||
long startTime = System.nanoTime(); | ||
while ((r = inputStream.read(buff)) != -1) { | ||
// Do some processing | ||
} | ||
long endTime = System.nanoTime(); | ||
|
||
return (endTime - startTime) / MAX_ITERATIONS; | ||
} catch (IOException e) { | ||
throw new UncheckedIOException("A problem occurred while reading from a file", e); | ||
} | ||
} | ||
|
||
} |
55 changes: 55 additions & 0 deletions
55
07-io-streams-and-files/snippets/src/bg/sofia/uni/fmi/mjt/io/ObjectStreamExample.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package bg.sofia.uni.fmi.mjt.io; | ||
|
||
import java.io.EOFException; | ||
import java.io.FileNotFoundException; | ||
import java.io.IOException; | ||
import java.io.ObjectInputStream; | ||
import java.io.ObjectOutputStream; | ||
import java.nio.file.Files; | ||
import java.nio.file.Path; | ||
|
||
public class ObjectStreamExample { | ||
|
||
public static void main(String... args) { | ||
Path filePath = Path.of("students.bin"); | ||
Student firstStudent = new Student("Gosho", 20); | ||
Student secondStudent = new Student("Stamat", 80); | ||
|
||
writeStudentsToFile(filePath, firstStudent, secondStudent); | ||
readStudentsFromFile(filePath); | ||
} | ||
|
||
private static void writeStudentsToFile(Path file, Student... students) { | ||
try (var objectOutputStream = new ObjectOutputStream(Files.newOutputStream(file))) { | ||
for (Student student : students) { | ||
objectOutputStream.writeObject(student); | ||
objectOutputStream.flush(); | ||
} | ||
} catch (IOException e) { | ||
throw new IllegalStateException("A problem occurred while writing to a file", e); | ||
} | ||
} | ||
|
||
private static void readStudentsFromFile(Path file) { | ||
try (var objectInputStream = new ObjectInputStream(Files.newInputStream(file))) { | ||
|
||
Object studentObject; | ||
while ((studentObject = objectInputStream.readObject()) != null) { | ||
System.out.println(studentObject); | ||
|
||
Student s = (Student) studentObject; | ||
System.out.println("Name " + s.name()); | ||
} | ||
|
||
} catch (EOFException e) { | ||
// EMPTY BODY | ||
} catch (FileNotFoundException e) { | ||
throw new IllegalStateException("The files does not exist", e); | ||
} catch (IOException e) { | ||
throw new IllegalStateException("A problem occurred while reading from a file", e); | ||
} catch (ClassNotFoundException e) { | ||
throw new RuntimeException(e); | ||
} | ||
} | ||
|
||
} |
6 changes: 6 additions & 0 deletions
6
07-io-streams-and-files/snippets/src/bg/sofia/uni/fmi/mjt/io/Student.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
package bg.sofia.uni.fmi.mjt.io; | ||
|
||
import java.io.Serializable; | ||
|
||
public record Student(String name, int age) implements Serializable { | ||
} |
Oops, something went wrong.