java 比较两个文件时如何忽略空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29896838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Ignore the white Spaces while compare two files?
提问by Dan
I want to create a Unit test method. Version of Java - 1.6
我想创建一个单元测试方法。Java 版本 - 1.6
@Test
public void TestCreateHtml() throws IOException{
final File output = parser.createHtml();
final File expected = new File("src/main/resources/head.jsp");
assertEquals("The files differ!", FileUtils.readLines(expected), FileUtils.readLines(output));
}
This test method doesn't work. The contents of both files are equals, but they have different number of white spaces.
这个测试方法不行。两个文件的内容是相等的,但它们有不同数量的空格。
How can I ignore the white spaces?
我怎样才能忽略空格?
回答by ioseb
If the problem is in leading/trailing white space:
如果问题出在前导/尾随空格中:
assertEquals(actual.trim(), expected.trim());
If problem is in file contents, only solution I can think of is to remove all white space from both inputs:
如果问题出在文件内容中,我能想到的唯一解决方案是从两个输入中删除所有空格:
assertEquals(removeWhiteSpaces(actual), removeWhiteSpaces(expected));
where removeWhiteSpaces() method looks like this:
其中 removeWhiteSpaces() 方法如下所示:
String removeWhiteSpaces(String input) {
return input.replaceAll("\s+", "");
}
回答by Magnar Myrtveit
If the problem is only leading/trailing white spaces, you can compare line by line after trimming both. This does not work if there can also be extra newlines in one file compared to the other.
如果问题只是前导/尾随空格,您可以在修剪两者后逐行比较。如果与另一个文件相比,一个文件中还有额外的换行符,这将不起作用。
@Test
public void TestCreateHtml() throws IOException{
final File output = parser.createHtml();
final File expected = new File("src/main/resources/head.jsp");
List<String> a = FileUtils.readLines(expected);
List<String> b = FileUtils.readLines(output);
assertEquals("The files differ!", a.size(), b.size());
for(int i = 0; i < a.size(); ++i)
assertEquals("The files differ!", a.get(i).trim(), b.get(i).trim());
}
回答by talex
Iterate over list and trim each line
遍历列表并修剪每一行
List<String> result = new ArrayList<String>();
for(String s: FileUtils.readLines(expected)) {
result.add(s.trim());
}
Same with other file.
与其他文件相同。
And then compare new lists.
然后比较新列表。
回答by user1794469
Just remove the leading and trailing whitespace before comparing:
在比较之前删除前导和尾随空格:
@Test
public void TestCreateHtml() throws IOException{
final File output = parser.createHtml();
final File expected = new File("src/main/resources/head.jsp");
assertEquals("The files differ!", FileUtils.readLines(expected).replaceAll("^\s+|\s+$", ""), FileUtils.readLines(output).replaceAll("^\s+|\s+$", ""));
}