使用Java源代码中的大型文本片段 [英] Working with large text snippets in Java source

查看:119
本文介绍了使用Java源代码中的大型文本片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么好方法可以在Java源代码中使用文本块(字符串)?许多其他语言都有 heredoc 语法,但Java没有。这使得使用输出大量静态标记的标记库以及需要对XML块进行比较的单元测试非常不方便。

Are there any good ways to work with blocks of text (Strings) within Java source code? Many other languages have heredoc syntax available to them, but Java does not. This makes it pretty inconvenient to work with things like tag libraries which output a lot of static markup, and unit tests where you need to assert comparisons against blocks of XML.

其他人解决这个问题吗?它甚至可能吗?或者我只是忍受它吗?

How do other people work around this? Is it even possible? Or do I just have to put up with it?

推荐答案

虽然您可以使用某些格式化程序来转换和嵌入任何文本文件或long literal
作为Java字符串(例如,换行符,必要的转义等),我真的不会想到你需要这些功能的频繁情况。

While you could use certain formatters to convert and embed any text file or long literal as a Java string (e.g., with newline breaks, the necessary escapes, etc.), I can't really think of frequent situations where you would need these capabilities.

软件的趋势通常是将代码与其运行的数据分开。大文本部分即使仅用于显示或比较,也是数据,因此通常存储在外部。读取文件(甚至将结果缓存在内存中)的成本相当低。国际化更容易。改变更容易。版本控制更容易。其他工具(例如,拼写检查程序)可以很容易地使用。

The trend in software is generally to separate code from the data it operates on. Large text sections, even if meant just for display or comparison, are data, and are thus typically stored externally. The cost of reading a file (or even caching the result in memory) is fairly low. Internationalization is easier. Changing is easier. Version control is easier. Other tools (e.g., spell checkers) can easily be used.

我同意在单元测试的情况下,你想要比较模拟的东西,你需要大比例文本比较。但是,当你处理这么大的文件时,你通常会有一些测试可以处理几个不同的大输入以产生几个大输出,那么为什么不让你的测试加载适当的文件而不是内联呢?

I agree that in the case of unit tests where you want to compare things against a mock you would need large scale text comparisons. However, when you deal with such large files you will typically have tests that can work on several different large inputs to produce several large outputs, so why not just have your test load the appropriate files rather than inline it ?

与XML相同。实际上,对于XML,我认为在许多情况下你会想要读取XML并构建一个DOM树然后进行比较,而不是进行可能受空白影响的文本比较。在单元测试中手动创建XML树是很难看的。

Same goes with XML. In fact, for XML I would argue that in many cases you would want to read the XML and build a DOM tree which you would then compare rather than do a text compare that can be affected by whitespaces. And manually creating an XML tree in your unit test is ugly.

这篇关于使用Java源代码中的大型文本片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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