• System.lineSeparator() 解决 append(“\r\n“) 换行符抛异常:No such file or diretory


    大家好,我是三叔,这期给大家说一下跨平台换行符的问题,很多读者刚开始接触导入导出文件,使用换行符可能都会出现此类问题。

    Java 具有跨平台的特性,如果在Java中把它们固定了,写成绝对路径,Java跨平台的特性就没有了。例如:\r\n 换行符。

    在 Windows 下的路径分隔符和 Linux 下的路径分隔符是不一样的,windows 下的文件路径是:\User\xxxx.txt
    而 Linux 路径下是:/User/xxxx.txt

    StringBuffer sb = new StringBuffer();
     sb.append("========测试========").append("\r\n");
     // === 文件流之类的处理
    
    • 1
    • 2
    • 3

    Java 提供了跨平台的换行符,根据系统进行自动的匹配:System.lineSeparator()

    StringBuffer sb = new StringBuffer();
     sb.append("========测试========").append(System.lineSeparator());
     // === 文件流之类的处理
    
    • 1
    • 2
    • 3

    System.lineSeparator()源码如下:可以看出,返回系统相关的行分隔符字符串。它总是返回相同的值——系统属性line.separator的初始值。
    在 UNIX 系统上,它返回 “\n”; 在 Microsoft Windows 系统上,它返回 “\r\n”。

        /**
         * Returns the system-dependent line separator string.  It always
         * returns the same value - the initial value of the {@linkplain
         * #getProperty(String) system property} {@code line.separator}.
         *
         * 

    On UNIX systems, it returns {@code "\n"}; on Microsoft * Windows systems it returns {@code "\r\n"}. * * @return the system-dependent line separator string * @since 1.7 */ public static String lineSeparator() { return lineSeparator; }

    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
  • 相关阅读:
    神经网络量化
    SpringMVC笔记——配置异常处理
    分布式ID之雪花算法
    我眼中的《视觉测量技术基础》
    保健食品市场前景如何?
    能快速构建和定制网络拓扑图的WPF开源项目-NodeNetwork
    Git的基本操作和原理
    JavaWeb-Session和Cookie
    【Linux】服务器恶意登录记录及解决方案
    Linux开发板网线连接电脑,ubuntu虚拟机桥接windows,实现三方互通
  • 原文地址:https://blog.csdn.net/weixin_49065828/article/details/134427530