The correct solution suggests we use try-with-resources to complete the task. I understand that's a more beautiful way, but I'd like to use the try-catch-finally formula just in order to better understand how all this works. So, the validator implies that I'm not using the newInputStream and newOutputStream methods of the Files class to read and write files (while I think I am using them in lines 19 & 20). Another requirement my code doesn't pass is that streams for reading and writing must be closed. Isn't that exactly what my final block is doing?
package en.codegym.task.pro.task15.task1504;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
/*
Mixed-up bytes
*/
public class Solution {
public static void main(String[] args) throws IOException {
Scanner console = new Scanner(System.in);
var path1 = Paths.get(console.nextLine());
var path2 = Paths.get(console.nextLine());
InputStream inputStream = Files.newInputStream(path1);
OutputStream outputStream = Files.newOutputStream(path2);
try {
byte[] inputBytes = inputStream.readAllBytes();
byte[] outputBytes = new byte[inputBytes.length];
int lastIndex = inputBytes.length - 1;
if (inputBytes.length % 2 == 0) {
for (int i = 0; i < lastIndex; i += 2) {
outputBytes[i + 1] = inputBytes[i];
outputBytes[i] = inputBytes[i + 1];
}
} else {
for (int i = 0; i < lastIndex - 1; i += 2) {
outputBytes[i + 1] = inputBytes[i];
outputBytes[i] = inputBytes[i + 1];
}
outputBytes[lastIndex] = inputBytes[lastIndex];
}
outputStream.write(outputBytes, 0, outputBytes.length);
} catch (IOException exIO) {
System.out.println("Something went wrong: " + exIO);
} finally {
inputStream.close();
outputStream.close();
}
}
}