写入文件时保留换行符 [英] keeping newline characters when writing a file

查看:118
本文介绍了写入文件时保留换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从数据库表中导出数据并将其写到文件中.可以从数据库中正确检索换行符,并在编写String时保留换行符(这样我就可以重新导入导出的数据).

I´m exporting data from a database table and writing it down in a file. Newline characters are correctly retrieved from the database and kept when writing the String (so I´m able to reimport the exported data).

我的问题是文件中的换行符是隐式的(即,它们以换行符显示).如果数据库值为字符串"line1 \ r \ n line2",则将该字符串直接发送到我的BufferedWriter + FileOutputStream的结果是 第1行 第2行"

My problem is that in the file the newline characters are implicit (i.e. they appear as line breaks). If the database value is the string "line1 \r\n line2", the result of directly sending this String to my BufferedWriter + FileOutputStream is "line1 line2"

有什么办法可以精确地将文件"line1 \ r \ n line2"的字符序列写入文件? (我已经尝试过bw.write(value.toCharArray())

Is there any way I can write to the file exactly the "line1 \r\n line2" sequence of characters? (I've already tried bw.write(value.toCharArray())

推荐答案

您可以将每个转义序列替换为双反斜杠:

You can replace every escape sequence with a double-backslash:

public static String escapeChars(String str) {
    char[][] escapes = {
            { '\n', 'n' },
            { '\r', 'r' },
            { '\f', 'f' },
            { '\b', 'b' },
            { '\t', 't' }
    };
    for (char[] escape : escapes) {
        str = str.replaceAll(Character.toString(escape[0]), "\\\\" + escape[1]);
    }
    return str;
}

可以容易地添加双撇号和单撇号转义,但是我在此答案中已将其省略.

Double- and single-apostrophe escaping can be added easily, but I've omitted it in this answer.

这篇关于写入文件时保留换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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