gpt4 book ai didi

java - 读写文件 - Java 空空间

转载 作者:行者123 更新时间:2023-12-01 17:26:42 25 4
gpt4 key购买 nike

我想从文件中读取数据并写入文件。输入文件如下

<ORLANDO>   <0%>
As I remember, Adam, it was upon this fashion bequeathed me by will but poor a thousand crowns, and, as thou sayest,
<ORLANDO>

"A s I r e m e m b e r A d a m i t w a s u p o n t h i s f a s h i o n b e q u e a t h e d m e b y w i l l b u t p o o r a t h o u s a n d c r o w n s a n d a s t h o u s a y e s t c h a r g e d m y b r o t h e r o n ..."

我编写了一个java程序来删除带有标签的行,并用空格替换任何标点符号。但是写出的每个字母之间都有一个空格,而且行之间也有很多空白行。如何去除它们? 。请帮忙。

String line=null;
try {
BufferedReader br=new BufferedReader( new FileReader("filename"));
PrintWriter writer = new PrintWriter(new FileWriter("filename"));
try {
while((line=br.readLine())!=null)
{

if(!line.contains("<"))
{
line=(line.replaceAll("\\p{Punct}",""));

writer.println(line);
writer.flush();


}
}
}

最佳答案

默认情况下,当您使用 PrintWriter 打开文件时,它会截断该文件。您可以将其设置为附加,但无论哪种方式,您都无法重写您正在以这种方式读取的文件。

相反,您应该创建一个新文件并写入该文件。完成后,您可以删除原始文件并重命名副本(如果完全相同,则删除副本)

But each letter that is written out has a space in between and also in between lines lots of blank lines are present.

如果您编写的是 UTF-16,但将其读取为 ASCII 或 UTF-8,则会发生这种情况。避免这种情况的方法是不使用 UTF-16,这不是默认值。

try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("filename"), StandardCharsets.UTF_8));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("filename.tmp"), StandardCharsets.UTF_8))) {
for(String line; (line = br.readLine())!=null;) {
pw.println(line.replaceAll("<[^>]+>", ""));
}
}

关于java - 读写文件 - Java 空空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14334794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com