.. 我的任务是实现一个输入流并返回一个密文,其中每个字符向前两个位置并且必须区分大小写。 例如:
Test
cipher
For
Fundamentals
Of
Programming
XYZ
zyx
CamelCase
DiScO
cipherText(file);
Vguv
ekrjgt
Hqt
Hwpfcogpvcnu
Qh
Rtqitcookpi
ZAB
baz
EcognEcug
FkUeQ
这是第一个必须返回密文的类,我在那里做了一些实现:
public class CipherCreator {
private CipherCreator() {
}
public static StringBuilder cipherText(File input) throws IOException {
StringBuilder strb = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(input));
String str = null;
while ((str = br.readLine()) != null) {
strb.append(str + "\n");
}
}
finally {
if (br != null) {
br.close();
}
}
strb.setLength(strb.length() - 1);
return strb;
}
我有第二类“TransformerInputStream”,我必须重写 read() 和 close() 方法并完成字符传输工作。
如何对字符进行加密,尤其是区分大小写的字符?
也许你可以让
TransformerInputStream
延长 InputStream
:
CipherCreator.java
:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class CipherCreator {
// Private constructor to prevent instantiation
private CipherCreator() {}
public static String cipherText(File inputFile) throws IOException {
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(inputFile, StandardCharsets.UTF_8));
TransformerInputStream transformerInputStream = new TransformerInputStream(br)) {
int ch;
while ((ch = transformerInputStream.read()) != -1) {
sb.append((char) ch);
}
}
return sb.toString();
}
}
TransformerInputStream.java
:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
public class TransformerInputStream extends InputStream {
private final BufferedReader reader;
private String currentLine;
private int charIndex;
public TransformerInputStream(BufferedReader reader) {
this.reader = reader;
this.charIndex = 0;
this.currentLine = null;
}
@Override
public int read() throws IOException {
if (currentLine == null || charIndex >= currentLine.length()) {
currentLine = reader.readLine();
if (currentLine == null) {
return -1; // End of stream
}
currentLine += "\n"; // Re-add newline
charIndex = 0;
}
char ch = currentLine.charAt(charIndex++);
return shiftCharacter(ch);
}
private int shiftCharacter(char ch) {
if (ch >= 'a' && ch <= 'z') {
return ((ch - 'a' + 2) % 26) + 'a';
} else if (ch >= 'A' && ch <= 'Z') {
return ((ch - 'A' + 2) % 26) + 'A';
} else {
return ch; // Non-alphabetic characters remain unchanged
}
}
@Override
public void close() throws IOException {
reader.close();
}
}
Main.java
:
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
File inputFile = new File("src/main/java/input.txt");
try {
String cipheredText = CipherCreator.cipherText(inputFile);
System.out.println(cipheredText);
} catch (IOException e) {
e.printStackTrace();
}
}
}
input.txt
:
Test
cipher
For
Fundamentals
Of
Programming
XYZ
zyx
CamelCase
DiScO
输出:
Vguv
ekrjgt
Hqt
Hwpfcogpvcnu
Qh
Rtqitcookpi
ZAB
baz
EcognEcug
FkUeQ