[读取文件时保持换行符
问题描述 投票:0回答:1
我想读取文件并对其进行修改,但是每当创建新文件时,所有内容都保持一行。因此,我的问题是如何在不删除换行符的情况下保留换行符?public class JavaProgram {
public static char[] caesar (int offset, char [] charArray) {
char [] size = new char [charArray.length];
for (int i = 0; i < charArray.length; i++) {
int crypt = (charArray[i] + offset);
size[i] = (char) (crypt);
}
return size;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String text = "";
StringBuilder convert = new StringBuilder();
Scanner keyboard = new Scanner (System.in);
File file = new File ("C:\\Users\\starfleet\\Desktop\\laboratory\\Java\\1DV506 - Problem Solving and Programming\\kk222sy_assignment4\\document.txt");
try {
Scanner input = new Scanner (file);
while (input.hasNextLine()) {
text = input.nextLine();
char [] arr = text.toCharArray();
char [] newArr = encrypt(3, arr);
for (int i = 0; i < newArr.length; i++) {
convert.append(newArr[i]);
} catch (IOException e) {
e.printStackTrace();
}
try {
// write file
PrintWriter printer = new PrintWriter (document);
printer.append(convert);
printer.close();
} catch (IOException e) {
e.printStackTrace();
}
java
file
printwriter
1个回答
0
投票
在写每一行时添加换行符。您的情况是在for循环后追加了加密字符:for (int i = 0; i < newArr.length; i++) {
convert.append(newArr[i]);
convert.append("\r\n");
[在Java中添加新行就像在字符串的末尾包含“ \ n”,“ \ r”或“ \ r \ n”一样简单,具体取决于您所使用的SO。
热门问题