java程序读取所有文本并消除空格和行

时间:2014-03-27 06:43:23

标签: java java-ee

我想编写一个java程序来读取文件中的所有文本但是没有空格和行...下面给出的是文件中的所有文本现在我想读取此文本并将其复制到其他文件

 var provinfo={"cdn":"//bluehost-
 cdn.com","domain":"xyz.com","name":"xyz","phone":["(888) 401-4678","(801) 

 765-9400"],"code":"bh"};

 provinfo.cdn = location.protocol + provinfo.cdn;

这样新文件中的结果文本就像

varprovinfo{"cdn":"//bluehostcdn.com","domain":"xyz.com","name":"xyz","phone["(888)401-4678","(801)765-9400"],"code":"bh"};provinfo.cdn=location.protocol+provinfo.cdn;

正如您所见,通过消除空格和线条将文本合并为单行。这就是我想要的。

scanner = new Scanner(new File("D://actual.txt"));
String a = scanner.useDelimiter("\\Z").next();
String b= a.replaceAll(" ", "");
String c = b.replaceAll("[\\r\\n]+\\s+", "");
System.out.println(c); 

我使用此代码在控制台上编写,但使用与fileouputstream相同的代码不起作用?

3 个答案:

答案 0 :(得分:1)

为了消除空格,有一个非常有用但被忽视的功能

yourString.trim()

但是,它不会消除线条。

答案 1 :(得分:0)

试试这个,

        Scanner scanner = new Scanner(file);
        StringBuilder stringBuilder = new StringBuilder();
        while (scanner.hasNext())
        {
            stringBuilder.append(scanner.next().replaceAll("\\s", "").replaceAll("\n", ""));
        }

        System.out.println(stringBuilder.toString());

答案 2 :(得分:0)

这是绝对正常的!!!与您的上述计划。

    File outputFile = new File("output.txt");
    outputFile.createNewFile();
    FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
    fileOutputStream.write(c.getBytes());
    fileOutputStream.close();

    // read again from disk to make sure
    Scanner scanner1 = new Scanner(new File(outputFile.getAbsolutePath()));
    System.out.println(scanner1.next());

输出:

varprovinfo={"cdn":"//bluehost-cdn.com","domain":"xyz.com","name":"xyz","phone":["(888)401-4678","(801)765-9400"],"code":"bh"};provinfo.cdn=location.protocol+provinfo.cdn;