用于存储在 csv 文件中的 Java 转义字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3335042/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:21:49  来源:igfitidea点击:

Java Escaping String for Storage in csv file

javacsvescaping

提问by Christian

If want to store user created strings in a csv file. Is there a preferred library to use for Escaping the string or should I write my own function?

如果要将用户创建的字符串存储在 csv 文件中。是否有用于转义字符串的首选库,还是应该编写自己的函数?

采纳答案by limc

I suggest you use one of the libraries recommended by the post(s) here. While it may seem easy to write your own CSV creator/parser, you are going to run into issues where you need to handle scenarios such as user strings with commas or quotes in them, which can sometimes be quite cumbersome. I used the following libraries and they worked fine:-

我建议您使用此处帖子推荐的库之一。虽然编写自己的 CSV 创建器/解析器似乎很容易,但您将遇到需要处理场景的问题,例如其中包含逗号或引号的用户字符串,这有时会非常麻烦。我使用了以下库,它们运行良好:-

回答by JavaSheriff

For anyone looking for code:
add this to your pom.xml

对于任何寻找代码的人:
将此添加到您的 pom.xml

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

Then use:

然后使用:

 String escaped = StringEscapeUtils.escapeCsv("tHIS String 'needs escaping'");
 System.out.println(escaped); //safe for csv

UPD:as of version 3.6, StringEscapeUtilsin commons-langdeprecated, so you have to use commons-textinstead:

UPD:作为3.6版本,StringEscapeUtilscommons-lang弃用,因此,你必须使用commons-text,而不是:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.6</version>
</dependency>

回答by YoK

If you are writing your own implementation , then here is RFC for you reference: http://tools.ietf.org/html/rfc4180

如果您正在编写自己的实现,那么这里是 RFC 供您参考:http: //tools.ietf.org/html/rfc4180

If your string are not too complicated you can easily develop small function rather than using some library. I have referenced above RFC and created small function for same purpose in one of my projects.

如果您的字符串不太复杂,您可以轻松开发小函数而不是使用某些库。我已经参考了上面的 RFC 并在我的一个项目中为相同的目的创建了小函数。

回答by facundofarias

I ended up using StringEscapeUtils, mostly because I already had the dependency in my project. Works like a charm! Cheers

我最终使用了StringEscapeUtils,主要是因为我的项目中已经有了依赖项。奇迹般有效!干杯