java - 读写文件 - Java 空空间

标签 java string file-io filewriter replaceall

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

<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/

相关文章:

c++ - 从文件中捕获和转换字符串并执行数值运算

java - 将 soap header 身份验证添加到 wsdl2java 生成的代码

java - 从 JSONArray Java 中删除条目

c++ - 搜索整数子串的超快速方法

java - 我是否需要为所有编写者/读者保留变量以手动关闭它们?

python - 在 Python 中将多个字符串写入 CSV 文件

java - 使用 Commons-Email 发送电子邮件到 Gmail

java - 我可以存储和读取 STOMP 队列/主题中的消息吗?

c# - C# 中的字符串清理

c# - 文字字符串赋值会像这样调用 String 构造函数吗?