将文本附加到现有文件而不覆盖它
Appending text to existing file without overwriting it
我正在向现有文件 NameList.txt
添加一些内容,其中已经包含一些文本。
但是当我 运行 程序时,它会在开始编写新内容之前删除所有现有内容。
注意:我也试着找文件结束行在哪里。例如。通过使用 while ((lines = reader.readLine()) == null)
,其中 lines
变量的类型为 String
.
public class AddBooks {
public static void main(String[] args) {
Path Source = Paths.get("NameList.txt");
Charset charset = Charset.forName("Us-ASCII");
try (
BufferedWriter write = Files.newBufferedWriter(Source, charset);
BufferedReader reader = Files.newBufferedReader(Source, charset);
) {
Scanner input = new Scanner(System.in);
String s;
String line;
int i = 0, isEndOfLine;
do {
System.out.println("Book Code");
s = input.nextLine();
write.append(s, 0, s.length());
write.append("\t \t");
System.out.println("Book Title");
s = input.nextLine();
write.append(s, 0, s.length());
write.append("\t \t");
System.out.println("Book Publisher");
s = input.nextLine();
write.append(s, 0, s.length());
write.newLine();
System.out.println("Enter more Books? y/n");
s = input.nextLine();
} while(s.equalsIgnoreCase("y"));
} catch (Exception e) {
// TODO: handle exception
}
}
}
我唯一的要求是向现有文件添加新内容。
像这样更改您的代码!
BufferedWriter write = Files.newBufferedWriter(Source, charset, StandardOpenOption.APPEND);
看看这个!
StandardOpenOption
第二..
while ((str = in.readLine()) != null)
附录..插入
writer.close();
之前
} while(s.equalsIgnoreCase("y"));
我正在向现有文件 NameList.txt
添加一些内容,其中已经包含一些文本。
但是当我 运行 程序时,它会在开始编写新内容之前删除所有现有内容。
注意:我也试着找文件结束行在哪里。例如。通过使用 while ((lines = reader.readLine()) == null)
,其中 lines
变量的类型为 String
.
public class AddBooks {
public static void main(String[] args) {
Path Source = Paths.get("NameList.txt");
Charset charset = Charset.forName("Us-ASCII");
try (
BufferedWriter write = Files.newBufferedWriter(Source, charset);
BufferedReader reader = Files.newBufferedReader(Source, charset);
) {
Scanner input = new Scanner(System.in);
String s;
String line;
int i = 0, isEndOfLine;
do {
System.out.println("Book Code");
s = input.nextLine();
write.append(s, 0, s.length());
write.append("\t \t");
System.out.println("Book Title");
s = input.nextLine();
write.append(s, 0, s.length());
write.append("\t \t");
System.out.println("Book Publisher");
s = input.nextLine();
write.append(s, 0, s.length());
write.newLine();
System.out.println("Enter more Books? y/n");
s = input.nextLine();
} while(s.equalsIgnoreCase("y"));
} catch (Exception e) {
// TODO: handle exception
}
}
}
我唯一的要求是向现有文件添加新内容。
像这样更改您的代码!
BufferedWriter write = Files.newBufferedWriter(Source, charset, StandardOpenOption.APPEND);
看看这个! StandardOpenOption
第二..
while ((str = in.readLine()) != null)
附录..插入
writer.close();
之前
} while(s.equalsIgnoreCase("y"));