PrintWriter 创建空文件
PrintWriter creates empty file
我有以下问题我想读取一个文件并将字母表中的每个字母向下移动 3 个位置。凯撒密码工作正常,我可以打印它,但每当我试图用 PrintWriter 将它传递到一个新文件时,该文件仍然是空的。
import java.io.IOException;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public static char[] encrypt (int offset, char [] charArray) {
char [] cryptArray = new char [charArray.length];
for (int i = 0; i < charArray.length; i++) {
int crypt = (charArray[i] + offset);
cryptArray[i] = (char) (crypt);
}
return cryptArray;
}
public static void main(String[] args) {
String text = "";
StringBuilder convert = new StringBuilder();
try {
File file = new File ("C:\PATH\file.txt");
Scanner input = new Scanner (file);
while (input.hasNextLine()) {
text = input.nextLine();
convert = new StringBuilder (text);
char [] arr = text.toCharArray();
char [] newArr = encrypt(3, arr);
for (int i = 0; i < newArr.length; i++) {
convert.append(newArr[i]).toString();
}
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
// write file
File outFile = new File ("C:\PATH\newfile.txt");
PrintWriter printer = new PrintWriter (outFile);
printer.print(convert);
printer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
删除循环中的 convert = new StringBuilder (text);
。它正在覆盖上一个循环中的数据
我有以下问题我想读取一个文件并将字母表中的每个字母向下移动 3 个位置。凯撒密码工作正常,我可以打印它,但每当我试图用 PrintWriter 将它传递到一个新文件时,该文件仍然是空的。
import java.io.IOException;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public static char[] encrypt (int offset, char [] charArray) {
char [] cryptArray = new char [charArray.length];
for (int i = 0; i < charArray.length; i++) {
int crypt = (charArray[i] + offset);
cryptArray[i] = (char) (crypt);
}
return cryptArray;
}
public static void main(String[] args) {
String text = "";
StringBuilder convert = new StringBuilder();
try {
File file = new File ("C:\PATH\file.txt");
Scanner input = new Scanner (file);
while (input.hasNextLine()) {
text = input.nextLine();
convert = new StringBuilder (text);
char [] arr = text.toCharArray();
char [] newArr = encrypt(3, arr);
for (int i = 0; i < newArr.length; i++) {
convert.append(newArr[i]).toString();
}
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
// write file
File outFile = new File ("C:\PATH\newfile.txt");
PrintWriter printer = new PrintWriter (outFile);
printer.print(convert);
printer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
删除循环中的 convert = new StringBuilder (text);
。它正在覆盖上一个循环中的数据