我目前正在通過一個在線java課程,其中的主題是關於使用輸入流進行讀寫的方式。具體來說,本課程演示如何使用用戶輸入的偏移來加密圖像文件,然後使用負偏移解密相同的圖像文件。爲什麼從文件輸入流讀取時,必須將字節轉換爲字節?
但是,在所提供的代碼中,我不明白關鍵線實際上做了什麼,以及它爲什麼會這樣做。根據我所能做的,它從FileInputStream
中讀取一個字節,並將其轉換爲一個字節,然後在將其轉移到文件之前通過文件輸出流寫出它。但是,由於我已經讀取了FileInputStream
中的一個字節,爲什麼我必須再次將它轉換爲一個字節?
我真的很感謝任何人對此有所瞭解。
謝謝!
import java.io.*;
import java.util.Scanner;
public class ReadingAndWritingStreamsNonText {
public static String imgFilePath = "C:\\JavaProjects\\BinaryStreams\\src\\MIM_BINARY_MEME.jpg";
public static String imgFilePath2 = "C:\\JavaProjects\\BinaryStreams\\src\\data.bin";
public static String imgFilePath3 = "C:\\JavaProjects\\BinaryStreams\\src\\MIM_BINARY_MEME_Decrypted.jpg";
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a shift to encrypt/decrypt the file:");
int shift = Integer.parseInt(input.nextLine());
try {
FileInputStream fis = null;
FileOutputStream fos = null;
PrintStream ps = null;
if (shift > 0) {
fis = new FileInputStream(imgFilePath);
fos = new FileOutputStream(imgFilePath2);
ps = new PrintStream(fos);
}
else {
fis = new FileInputStream(imgFilePath2);
fos = new FileOutputStream(imgFilePath3);
ps = new PrintStream(fos);
}
boolean done = false;
while (!done) {
//read in the file
int next = fis.read();
if (next == -1) {
done = true;
}
else {
//encrypt or decrypt based on shift
**ps.write(((byte) next) + shift);** <--- this line
}
}
ps.close();
ps = null;
fos.close();
fos = null;
fis.close();
fis = null;
}
catch (IOException ioex) {
ioex.printStackTrace();
}
System.out.println("Operation Completed");
}
}