Java 支持多行字符串吗?

2024-05-07

来自 Perl,我肯定缺少在源代码中创建多行字符串的“here-document”方法:

$string = <<"EOF"  # create a three-line string
text
text
text
EOF

在 Java 中,当我从头开始连接多行字符串时,我必须在每一行上使用繁琐的引号和加号。

有哪些更好的选择?在属性文件中定义我的字符串?

Edit:两个答案都说 StringBuilder.append() 比加号更好。谁能详细解释一下他们为什么这么认为?对我来说,它看起来一点也不更好。我正在寻找一种方法来解决多行字符串不是一流语言构造这一事实,这意味着我绝对不想用方法调用替换一流语言构造(带加号的字符串连接)。

Edit:为了进一步澄清我的问题,我根本不关心性能。我担心可维护性和设计问题。



NOTE:这个答案适用于 Java 14 及更早版本。

Java 15 中引入了文本块(多行文字)。请参阅这个答案 https://stackoverflow.com/a/50155171/466862了解详情。


听起来你想要做一个多行文字,这在 Java 中不存在。

你最好的选择是字符串+就在一起了人们提到的其他一些选项(StringBuilder、String.format、String.join)只有在您从字符串数组开始时才会更好。

考虑一下:

String s = "It was the best of times, it was the worst of times,\n"
         + "it was the age of wisdom, it was the age of foolishness,\n"
         + "it was the epoch of belief, it was the epoch of incredulity,\n"
         + "it was the season of Light, it was the season of Darkness,\n"
         + "it was the spring of hope, it was the winter of despair,\n"
         + "we had everything before us, we had nothing before us";

Versus StringBuilder:

String s = new StringBuilder()
           .append("It was the best of times, it was the worst of times,\n")
           .append("it was the age of wisdom, it was the age of foolishness,\n")
           .append("it was the epoch of belief, it was the epoch of incredulity,\n")
           .append("it was the season of Light, it was the season of Darkness,\n")
           .append("it was the spring of hope, it was the winter of despair,\n")
           .append("we had everything before us, we had nothing before us")
           .toString();

Versus String.format():

String s = String.format("%s\n%s\n%s\n%s\n%s\n%s"
         , "It was the best of times, it was the worst of times,"
         , "it was the age of wisdom, it was the age of foolishness,"
         , "it was the epoch of belief, it was the epoch of incredulity,"
         , "it was the season of Light, it was the season of Darkness,"
         , "it was the spring of hope, it was the winter of despair,"
         , "we had everything before us, we had nothing before us"
);

与 Java8 对比String.join() http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-:

String s = String.join("\n"
         , "It was the best of times, it was the worst of times,"
         , "it was the age of wisdom, it was the age of foolishness,"
         , "it was the epoch of belief, it was the epoch of incredulity,"
         , "it was the season of Light, it was the season of Darkness,"
         , "it was the spring of hope, it was the winter of despair,"
         , "we had everything before us, we had nothing before us"
);

如果您想要特定系统的换行符,您需要使用System.lineSeparator(),或者你可以使用%n in String.format.

另一种选择是将资源放入文本文件中,然后只读取该文件的内容。这对于非常大的字符串来说是更可取的,以避免不必要地使类文件膨胀。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java 支持多行字符串吗? 的相关文章

  • 从 Android 函数更新 Textview

    有人可以告诉我如何从函数更新 Android Textview 控件吗 我在互联网上进行了深入搜索 看到很多人都问同样的问题 我测试了线程但无法工作 有人有一个简单的工作示例吗 例如 调用一个函数 在循环中运行多次 并且该函数在 TextV
  • Selector.close() 是否关闭所有客户端套接字?

    我是 nio 套接字的新手 我已经使用 nio 套接字编写了一个服务器 现在我正在尝试编写关闭钩子以确保通过清理资源正常退出 我的问题是Selector close 方法关闭所有客户端套接字 如果没有 请告诉我如何访问所有客户端套接字 而无
  • ZeroDateTimeBehavior=convertToNull 在使用 hibernate 的 jdbc url 中不起作用

    通过 extern 属性文件 url 指定如下 jdbc mariadb xxxxx 3306 xxxxx zeroDateTimeBehavior convertToNull 连接工作正常并且能够查询数据库 通过休眠 我创建了一个映射到带
  • 如何杀死 Java Future?

    我正在开发的服务使用 Future 来并行运行多个任务 每个任务最多可能需要一分钟才能完成 然而 外部库似乎有问题 因为在某些情况下 2 的时间 它不会返回 在这些情况下 我想给出 2 分钟的等待时间 如果还没有返回 我想杀死 future
  • 传递自定义类型查询参数

    如何接受自定义类型查询参数 public String detail QueryParam request final MYRequest request 上面的行在启动服务器时出现错误 jersey server model ModelV
  • 用于制作代码编辑器的 JavaFX 相当于 JSyntaxPane 的什么?

    以前在 Swing 中 我使用过JSyntaxPane用于制作一个小型 Java 源代码编辑器 为了练习 我决定用 JavaFX 重做整个项目并添加对更多语言的支持 最好是尽可能多 不过好像没有什么类似的JSyntaxPane 一些研究让我
  • Google 表格使用 API 密钥而不是 client_secret.json

    In the QuickStart java示例Java 快速入门 https developers google com sheets api quickstart java他们使用OAuth client ID识别该应用程序 这会弹出一
  • 使用正则表达式验证电子邮件的最大长度

    我找到了用于电子邮件验证的正则表达式 a z0 9 a z0 9 a z0 9 a z0 9 a z 2 4 我希望电子邮件的最大长度为 20 个字符 因此我将其更改为 a z0 9 a z0 9 a z0 9 a z0 9 a z 2 4
  • 是否可以使用 Apache Tika 提取表信息?

    我正在寻找 pdf 和 MS Office 文档格式的解析器 以从文件中提取表格信息 当我看到 Apache Tika 时 正在考虑编写单独的实现 我能够从任何这些文件格式中提取全文 但我的要求是提取表格数据 我希望有 2 列采用键值格式
  • 如何检查单词是否在wordNet中

    我开始了解wordNet直到我知道我找到了synonymous对于一个特定的词 现在我有一个文件 我想使用标记化该文本n gram例如 String s I like to wear tee shirt 使用后n gram这将是 I lik
  • 我的 Kafka 流应用程序刚刚退出,代码为 0,什么也不做

    为了尝试 Kafka 流 我这样做了 public static void main String args final StreamsBuilder builder new StreamsBuilder final Properties
  • 为休息服务实施 JUnit 测试

    我必须为我的休息服务实现一些 JUnit 测试 例如 这是我的休息服务之一 Path dni fe public class HelloWorld POST Path home Consumes MediaType APPLICATION
  • 如何在 JmsMessagingTemplate.sendAndReceive 上设置等待超时

    我在 MVC 控制器中使用 JmsMessagingTemplate 的 sendAndReceive 但如果没有发送回复消息 它似乎会永远等待回复 该文档指出 返回 回复 如果无法接收消息 例如由于超时 则可能为 null 然而 我只是不
  • 在约束验证器中使用 Guice 进行依赖注入

    我有一个在 ConstraintValidator 的实现中注入类的用例 我正在使用 Google guice 进行依赖项注入 目前无法在验证器内注入 我的场景的简化形式 内部模块 Provides Singleton public Ser
  • 在 Spring MVC 中将请求写入文件

    我希望能够将整个请求写入 Spring MVC 控制器中的文件 我已尝试以下操作 但即使我使用大量参数发出 POST 请求 文件也始终为空 RequestMapping method RequestMethod POST value pay
  • 如何更改 JAX-WS Web 服务的地址位置

    我们目前已经公开了具有以下 URL 的 JAX RPC Web 服务 http xx xx xx xx myservice MYGatewaySoapHttpPort wsdl http xx xx xx xx myservice MYGa
  • Spring MVC:通用 DAO 和服务类

    我正在 Spring MVC 中编写网页 我使用 Generic DAO 编写了所有 DAO 现在我想重写我的服务类 我该如何写 通用服务 我的 DAO 如下 DAO package net example com dao import j
  • 亚马逊 Linux - 安装 openjdk-debuginfo?

    我试图使用jstack在 ec2 实例上amazon linux 所以我安装了openjdk devel包裹 sudo yum install java 1 7 0 openjdk devel x86 64 但是 jstack 引发了异常j
  • 假布尔值=真?

    我在一本书中找到了这段代码 并在 Netbeans 中执行了它 boolean b false if b true System out println true else System out println false 我只是不明白为什
  • Graphics2D setfont() 严重减慢了 java 应用程序的启动速度

    我正在用java制作一个游戏 它每秒刷新60次 每次执行循环时 我都会使用 g2d 来绘制图像和字符串 如果我这样做的话一切都会很好g2d setFont new Font Arial Font PLAIN 8 和抽绳 这将是正常的 但如果

随机推荐

  • 如何在Java中从一组选定的颜色中输出随机颜色? (安卓)

    因此 我希望每当用户输入答案时都为字符串赋予随机颜色 我的问题是 我不确定如何使字符串的随机颜色成为特定范围的颜色 例如 如果我希望字符串随机变成蓝色 红色 绿色 粉色 白色或棕色 只有这些颜色 没有其他颜色 到目前为止 我已经使用以下代码
  • Python:如何将包含对象的列表保存在文件中?

    我尝试创建不同的对象 使用类和对象 并将它们保存在文件中以便稍后编辑或检索它们 然而这就是它的样子 GlobalCategories GlobalContent def LoadData x y import pickle with ope
  • 为什么自动关闭脚本元素不起作用?

    浏览器无法正确识别的原因是什么 只有这一点是公认的 这是否打破了 XHTML 支持的概念 注意 此声明至少对于所有 IE 6 8 beta 2 都是正确的 XHTML 1 规范的非规范性附录 HTML 兼容性指南 指出 3 元素最小化和空元
  • 应用程序和插件修订,使 Origen 应用程序生产做好准备

    我们的开发应用程序有大约 12 个自制插件和许多 Origen gems 需要从开发转向生产级质量 我看到许多不同的主题开始here http origen sdk org origen guides misc revisioncontro
  • 如何在网页上使用 Apple 新的 San Francisco 字体

    我想在网站上使用新的 San Francisco 字体 我试过了 font San Francisco Helvetica Arial san serif 无济于事 我已经尝试过以下问题的答案这个问题 https stackoverflow
  • matplotlib - 模块“sip”没有属性“setapi”

    我刚刚设置了带有所有 Python 扩展的 VS Code 通过 Anaconda Python 版本为 3 8 3 解释器是 venv 当我运行这段代码时 import matplotlib pyplot as plt 错误显示 Exce
  • MySQL 不将 ı 视为 i?

    我在 MySQL 5 7 27 中有一个用户表utf8mb4 unicode ci整理 不幸的是 没有像 i 那样进行线程化 以下查询将找不到Y lmaz select id from users where name Yilmaz 我对其
  • 转换为 id 与真实类类型之间的差异,目标 C

    以下 2 种说法有什么区别 UILabel mainLabel id cell viewWithTag 10 and UILabel mainLabel UILabel cell viewWithTag 10 简短的回答 没有 这两种强制转
  • 如何对URL参数传输的秘密数据进行编码/加密?

    故事是这样的 我必须将一些机密信息从一个脚本传递到另一个脚本 在第一个脚本中 我需要先加密数据 然后再加密have to将加密数据附加到 GET 请求中并将其发送到另一个脚本 URL 看起来像这样 http mydomain com mys
  • 阻止 OpenGL.framework 在 Cocoa 应用程序中加载

    我的应用程序链接到这些框架 Cocoa Framework AppKit Framework CoreData Framework Foundation Framework 请注意 OpenGL Framework 是NOT已链接 但是 设
  • 如何在iframe中隐藏滚动条,但仍然能够滚动

    我的一个页面上有一个 iframe 其中有另一个页面 我想隐藏滚动条 但我找不到任何解决方案 我尝试过overflow hidden 但它不起作用 见下面的代码 CSS代码 iframe overflow hidden 由于您没有指定是否需
  • Pandas 随机样本删除

    我知道DataFrame sample 但是我怎样才能做到这一点并从数据集中删除样本呢 注意 据我所知 这与替换采样无关 例如这里是精华我想要实现的目标 这实际上不起作用 len df 1000 df subset df sample 30
  • mongoDB 中的游标隔离

    首先请原谅我问了一个愚蠢的问题 但我是 mongodb 和学习游标的新手 我有一个问题 为什么我们需要游标隔离 手册说 如果文档发生更改 对文档的干预写入操作可能会导致游标多次返回该文档 我无法理解这一点 如果有人可以提供更多说明或举一些例
  • 使用 pandas 插值将每月值转换为每日值

    我有 1000 列的 12 个平均每月值 我想使用 pandas 将数据转换为每日数据 我尝试过使用插但我得到了从 31 01 1991 到 31 12 1991 的每日值 这并不涵盖全年 一月份的值没有得到 我用了日期范围用于我的数据框的
  • R 编程:创建堆叠条形图,每个堆叠条形具有可变颜色

    我正在尝试创建一个堆叠条形图 每个堆叠条形图中的颜色可变 也就是说 一个条形图在红色上方显示蓝色 下一个条形图在紫色上方显示红色 等等 我还想保留堆叠图表的功能 十分感谢大家 Adam 下图 使用上面的代码创建 显示了主要汽车制造商生产的汽
  • 使用 Entity Framework 6 强制两列之一不为 NULL

    我有一个如下表 Table tblStore public class Store Key DatabaseGenerated DatabaseGeneratedOption Identity public Guid Id get set
  • 如何获取 ndarray 的 x 和 y 维度 - Numpy / Python

    我想知道是否可以分别获取 ndarray 的 x 和 y 维度 我知道我可以使用ndarray shape获取表示维度的元组 但如何在 x 和 y 信息中分离它 先感谢您 您可以使用元组拆包 y x a shape
  • 将 SAML 令牌与 Web 服务 (wsdl) 结合使用

    我已从提供商处获得了 wsdl 文件和 pfx 我致电 IdP 并获取 SAML 令牌 现在我需要将该令牌传递给 WebService 如何使用 SAML 令牌来处理 WebService 我正在使用 NET 4 5 在以下两篇文章的帮助下
  • 不会将字符串转换为十进制 C#(输入字符串的格式不正确。)

    Visual Studio 不会将我的字符串转换为十进制 错误 输入字符串的格式不正确 Code string test 123 95 decimal test1 decimal parse test string being an int
  • Java 支持多行字符串吗?

    来自 Perl 我肯定缺少在源代码中创建多行字符串的 here document 方法 string lt lt EOF create a three line string text text text EOF 在 Java 中 当我从头