删除所有空格和空行

时间:2011-08-25 12:49:46

标签: java file whitespace blank-line

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

输入:

qwe
    qweqwe
  qwe



qwe

输出:

qwe
qweqwe
qwe
qwe

谢谢!

8 个答案:

答案 0 :(得分:14)

这样的事情怎么样:

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();

注意 - 未经测试,可能不是完美的语法,但为您提供了一个想法/方法可以遵循。

请参阅以下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

答案 1 :(得分:4)

看看trim()函数

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#trim()

此外,一些代码会有所帮助......

答案 2 :(得分:3)

...
Scanner scanner = new Scanner(new File("infile.txt"));
PrintStream out = new PrintStream(new File("outfile.txt"));
while(scanner.hasNextLine()){
    String line = scanner.nextLine();
    line = line.trim();
    if(line.length() > 0)
        out.println(line);
}
...

答案 3 :(得分:1)

这是我第一次回答此站点中的问题,因此请耐心等待,经过大量搜索,我发现此方法很适合我。

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

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

答案 4 :(得分:0)

删除每一行的空格,不要考虑空行和空行:

String line =  buffer.readLine();

while (line != null) {
    line = removeSpaces(line);        
    //ignore empty lines
    if (line.isEmpty()) return;

      ....code....


    line =  buffer.readLine();
} 




public String removeSpaces (String arg)
{
    Pattern whitespace = Pattern.compile("\\s");
    Matcher matcher = whitespace.matcher(arg);
    String result = "";
    if (matcher.find()) {
        result = matcher.replaceAll("");
    }
    return result;
}

答案 5 :(得分:0)

  

用于删除同一文件中的空行。

public static void RemoveEmptyLines(String FilePath) throws IOException
{
    File inputFile = new File(FilePath);
    BufferedReader reader = new BufferedReader(new FileReader(inputFile));
    String inputFileReader;
    ArrayList <String> DataArray = new ArrayList<String>();
    while((inputFileReader=reader.readLine())!=null)
    {
        if(inputFileReader.length()==0)
        {
            continue;
        }
        DataArray.add(inputFileReader);
    }
    reader.close();

    BufferedWriter bw = new BufferedWriter(new FileWriter(FilePath));
    for(int i=0;i<DataArray.size();i++)
    {
        bw.write(DataArray.get(i));
        bw.newLine();
        bw.flush();
    }
    bw.close();
}

答案 6 :(得分:0)

public class SalesforceRestStarter {

    //private static final String TOKEN_URL =  "https://login.salesforce.com/services/oauth2/token";
    private static final String TOKEN_URL =  "https://ap5.salesforce.com/services/oauth2/token";

    public static void main(String[] args) throws Exception {

        try {
            System.out.println("===========================================================================================");
            // login
            final CloseableHttpClient httpclient = HttpClients.createDefault();

            final List<NameValuePair> loginParams = new ArrayList<NameValuePair>();
            loginParams.add(new BasicNameValuePair("client_id", "37506609426920XXX"));
            loginParams.add(new BasicNameValuePair("client_secret", "3MVG9d8..z.hDcPJZPIzGJ5UZDqJOJY.3R6RBM8sJAF8PyTtdTE.XXXXXXXXXXXXXXXX"));
            loginParams.add(new BasicNameValuePair("grant_type", "password"));
            loginParams.add(new BasicNameValuePair("username", "XXXXXXX@xy.com"));
            loginParams.add(new BasicNameValuePair("password", "XXXXXXX"));

            final HttpPost post = new HttpPost(TOKEN_URL);
            post.setEntity(new UrlEncodedFormEntity(loginParams));

            final HttpResponse loginResponse = httpclient.execute(post);
            System.out.println("RESPONSE :: ==> "+loginResponse.getStatusLine());

            // parse
            final ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);

            final JsonNode loginResult = mapper.readValue(loginResponse.getEntity().getContent(), JsonNode.class);
            final String accessToken = loginResult.get("access_token").asText();
            final String instanceUrl = loginResult.get("instance_url").asText();

            // query contacts
            final URIBuilder builder = new URIBuilder(instanceUrl);
            builder.setPath("/services/data/v40.0/query/").setParameter("q", "SELECT Id, Name FROM Contact");

            final HttpGet get = new HttpGet(builder.build());
            get.setHeader("Authorization", "Bearer " + accessToken);

            final HttpResponse queryResponse = httpclient.execute(get);

            final JsonNode queryResults = mapper.readValue(queryResponse.getEntity().getContent(), JsonNode.class);

            System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(queryResults));
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

答案 7 :(得分:0)

我想你只想要一个正则表达式:

        txt= txt.replaceAll("\\n\\s*\\n", "\n");  //remove empty lines
        txt= txt.replaceAll("\\s*", "");  //remove whitespaces

至于读/写文件,还有很多其他资源可以了解如何做到这一点。