我想在java中基本上删除一个文件。只需逐行读取文件,并将字符的值更改为“char + = key”,其中key是整数。 问题是如果我使用大于或等于2的键,它就不再起作用了。
public void encryptData(int key) {
System.out.println("Encrypt");
try {
BufferedReader br = new BufferedReader(new FileReader("encrypted.data"));
BufferedWriter out = new BufferedWriter(new FileWriter("temp_encrypted.data"));
String str;
while ((str = br.readLine()) != null) {
char[] str_array = str.toCharArray();
// Encrypt one line
for (int i = 0; i < str.length(); i++) {
str_array[i] += key;
}
// Put the line in temp file
str = String.valueOf(str_array);
out.write(str_array);
}
br.close();
out.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
解密函数是相同的,但输入/输出文件互换,而不是添加键值,我减去它。
我通过char检查char,实际上,当我使用键值&gt;时,标题会搞砸。 1.任何想法?是因为超出了char的最大值吗?
答案 0 :(得分:1)
你基本上是在实现一个通用的凯撒密码。 向字符添加数字可能会将字符更改为换行符等,如果使用BufferedReader将其读回,则无效。
最好将文本操作为字节流,以正确编码和解码换行符和任何非ASCII字符。
public void encryptData(int key) {
System.out.println("Encrypt");
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("raw-text.data"));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("temp_encrypted.data"));
int ch;
while((ch = in.read()) != -1) {
// NOTE: write(int) method casts int to byte
out.write(ch + key);
}
out.close();
in.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public void decryptData(int key) {
System.out.println("Decrypt");
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("temp_encrypted.data"));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("decrypted.data"));
int ch;
while((ch = in.read()) != -1) {
out.write(ch - key);
}
out.close();
in.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}