gpt4 book ai didi

java - 为什么从文件输入流读取时必须转换为字节?

转载 作者:行者123 更新时间:2023-12-02 08:38:11 24 4
gpt4 key购买 nike

我目前正在学习在线 Java 类(class),其中主题是关于使用输入流进行阅读和写作。具体来说,本类(class)演示了使用用户输入的移位来加密图像文件,然后使用负移位来解密同一图像文件。

但是,在提供的代码中,我不明白关键行实际上做了什么,以及为什么它会这样做。据我所知,它从 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");
}
}

最佳答案

因为InputStream.read()返回一个 int 而不是 byte

请注意,当到达流末尾时,此方法将返回 -1,如果读取了字节,则返回 0 到 255 范围内的值,如 API 文档所述:

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

int 需要强制转换才能转换为 byte,因为 int 是 32 位,而 byte 只有 8 位。如果不进行强制转换,则无法进行缩小转换(这会丢弃 int 的高 24 位)。

关于java - 为什么从文件输入流读取时必须转换为字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31227940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com