и 2-how Код? 2 **? Не знаю, когда код хочет проверить соединение, это проверяет только 206 и 200 код ответа статуса, но почему мы просто проверяем код успеха? 2 **? < /p>
и 2-how
Код: Выделить всё
public class ResumableDownloader {
public static void download(String fileURL, String savePath) throws IOException {
File file = new File(savePath);
long existingFileSize = file.exists() ? file.length() : 0;
URL url = new URL(fileURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set Range header to resume download
conn.setRequestProperty("Range", "bytes=" + existingFileSize + "-");
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_PARTIAL || responseCode == HttpURLConnection.HTTP_OK) {
try (InputStream in = conn.getInputStream();
RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
System.out.println(existingFileSize);
raf.seek(existingFileSize); // Move to the end of existing file
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
raf.write(buffer, 0, bytesRead);
}
System.out.println("Download complete.");
}
} else {
System.out.println("Server does not support partial content. Response code: " + responseCode);
}
conn.disconnect();
}
public static void main(String[] args) throws IOException {
String fileURL = "https://pdn.sharezilla.ir/com.rar";
String savePath = "largefile.rar";
download(fileURL, savePath);
}
}
public class http {
public static void main(String[] args) throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
// 2. Build request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.header("Accept", "application/json")
.GET()
.build();
// 3. Send request and get response
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
// 4. Print status and body
System.out.println("Status: " + response.statusCode());
System.out.println("Body: " + response.body());
}
}
public class FileCrud {
public static void main(String[] args) throws IOException {
Path path = Paths.get("src/main/java/org/example/tt.txt");
if (!Files.exists(path)) {
Files.createFile(path);
}
// 1. WRITE (create or overwrite)
Files.write(path, "Hello World\n".getBytes());
System.out.println("Written: Hello World");
// // 2. READ
List lines = Files.readAllLines(path);
System.out.println("Read: " + lines);
//
// 3. UPDATE (read → modify → write back)
lines.stream() // Stream of lines
.map(line -> line.split(",")) // Stream
.forEach(parts -> Arrays.stream(parts)
.map(String::trim)
.forEach(p -> System.out.print(p + " | ")));
// // 4. DELETE
Files.deleteIfExists(path);
System.out.println("File deleted");
}
}
public class PasswordManager {
private String storedSalt;
private String storedHash;
// Generate salt
private String generateSalt() {
byte[] salt = new byte[16];
new SecureRandom().nextBytes(salt);
return Base64.getEncoder().encodeToString(salt);
}
// Hash password with salt
private String hashPassword(String password, String saltBase64) throws Exception {
byte[] salt = Base64.getDecoder().decode(saltBase64);
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(salt);
byte[] hashed = md.digest(password.getBytes());
return Base64.getEncoder().encodeToString(hashed);
}
// Store password
public void storePassword(String password) throws Exception {
storedSalt = generateSalt();
storedHash = hashPassword(password, storedSalt);
System.out.println("Stored Salt: " + storedSalt);
System.out.println("Stored Hash: " + storedHash);
}
// Verify password
public boolean verifyPassword(String inputPassword) throws Exception {
String inputHash = hashPassword(inputPassword, storedSalt);
return inputHash.equals(storedHash);
}
// Demo
public static void main(String[] args) throws Exception {
PasswordManager manager = new PasswordManager();
String originalPassword = "MohsenSecret";
manager.storePassword(originalPassword);
String testPassword = "MohsenSecret"; // Try changing this
if (manager.verifyPassword(testPassword)) {
System.out.println("✅ Password is correct");
} else {
System.out.println("❌ Password is incorrect");
}
}
}
public class RSAExample {
public static void main(String[] args) throws Exception {
// Generate RSA key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair pair = keyGen.generateKeyPair();
PublicKey publicKey = pair.getPublic();
PrivateKey privateKey = pair.getPrivate();
// Encrypt
String message = "Hello Mohsen!";
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = encryptCipher.doFinal(message.getBytes());
String encrypted = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println("Encrypted: " + encrypted);
// Decrypt
Cipher decryptCipher = Cipher.getInstance("RSA");
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = decryptCipher.doFinal(Base64.getDecoder().decode(encrypted));
String decrypted = new String(decryptedBytes);
System.out.println("Decrypted: " + decrypted);
}
}
public class CompletableFutureExample {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(3);
CompletableFuture future1 = CompletableFuture.supplyAsync(() -> {
System.out.printf("in 1");
sleep(10000);
return "Task 1 completed";
}, executor);
CompletableFuture future2 = CompletableFuture.supplyAsync(() -> {
sleep(12000);
System.out.printf("in 2");
return "Task 2 completed";
}, executor);
CompletableFuture future3 = CompletableFuture.supplyAsync(() -> {
System.out.printf("in 3");
sleep(15000);
return "Task 3 completed";
}, executor);
// Wait for all futures to complete
CompletableFuture allFutures = CompletableFuture.allOf(future1, future2, future3);
// When all are done, collect results
allFutures.thenRun(() -> {
List results = Arrays.asList(future1, future2, future3).stream()
.map(CompletableFuture::join)
.toList();
results.forEach(System.out::println);
}).join(); // Block until all are done
executor.shutdown();
}
private static void sleep(int millis) {
try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
public class SortAlgorithms {
// 🔢 Bubble Sort
public static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++)
for (int j = 0; j < arr.length - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(arr, j, j + 1);
}
// 🧠 Selection Sort
public static void selectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[minIdx])
minIdx = j;
swap(arr, i, minIdx);
}
}
// 🚀 Insertion Sort
public static void insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int key = arr[i], j = i - 1;
while (j >= 0 && arr[j] > key)
arr[j + 1] = arr[j--];
arr[j + 1] = key;
}
}
// ⚡ Merge Sort
public static void mergeSort(int[] arr) {
if (arr.length < 2) return;
int mid = arr.length / 2;
int[] left = new int[mid], right = new int[arr.length - mid];
System.arraycopy(arr, 0, left, 0, mid);
System.arraycopy(arr, mid, right, 0, arr.length - mid);
mergeSort(left);
mergeSort(right);
merge(arr, left, right);
}
private static void merge(int[] arr, int[] left, int[] right) {
int i = 0, j = 0, k = 0;
while (i < left.length && j < right.length)
arr[k++] = (left[i] = 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i > 0; i--) {
swap(arr, 0, i);
heapify(arr, i, 0);
}
}
private static void heapify(int[] arr, int n, int i) {
int largest = i, left = 2 * i + 1, right = 2 * i + 2;
if (left < n && arr[left] > arr[largest]) largest = left;
if (right < n && arr[right] > arr[largest]) largest = right;
if (largest != i) {
swap(arr, i, largest);
heapify(arr, n, largest);
}
}
// 🛠️ Utility: Swap
private static void swap(int[] arr, int i, int j) {
int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;
}
// 🧪 Test Runner
public static void main(String[] args) {
int[] data = {5, 2, 9, 1, 5, 6};
System.out.println("Original: ");
printArray(data);
bubbleSort(data.clone());
System.out.println("Bubble Sort:");
printArray(data);
selectionSort(data.clone());
System.out.println("Selection Sort:");
printArray(data);
insertionSort(data.clone());
System.out.println("Insertion Sort:");
printArray(data);
int[] mergeData = data.clone();
mergeSort(mergeData);
System.out.println("Merge Sort:");
printArray(mergeData);
int[] quickData = data.clone();
quickSort(quickData);
System.out.println("Quick Sort:");
printArray(quickData);
int[] heapData = data.clone();
heapSort(heapData);
System.out.println("Heap Sort:");
printArray(heapData);
}
private static void printArray(int[] arr) {
for (int num : arr) System.out.print(num + " ");
System.out.println();
}
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... downloader