删除所有空格和空行 [英] Remove all blank spaces and empty lines

查看:106
本文介绍了删除所有空格和空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Java SE从txt文件中删除所有空格和空行?

How to remove all blank spaces and empty lines from a txt File using Java SE?

输入:

qwe
    qweqwe
  qwe



qwe

输出:

qwe
qweqwe
qwe
qwe

谢谢!

推荐答案

这样的事情如何?

FileReader fr = new FileReader("infile.txt"); 
BufferedReader br = new BufferedReader(fr); 
FileWriter fw = new FileWriter("outfile.txt"); 
String line;

while((line = br.readLine()) != null)
{ 
    line = line.trim(); // remove leading and trailing whitespace
    if (!line.equals("")) // don't write out blank lines
    {
        fw.write(line, 0, line.length());
    }
} 
fr.close();
fw.close();

注意-未经测试,可能不是完美的语法,但可以为您提供思路/方法.

Note - not tested, may not be perfect syntax but gives you an idea/approach to follow.

请参阅以下JavaDocs以作参考: http://download.oracle.com/javase/7 /docs/api/java/io/FileReader.html http://download.oracle.com/javase/7 /docs/api/java/io/FileWriter.html

See the following JavaDocs for reference purposes: http://download.oracle.com/javase/7/docs/api/java/io/FileReader.html http://download.oracle.com/javase/7/docs/api/java/io/FileWriter.html

这篇关于删除所有空格和空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆