StandardLineSeparator.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.io;

  18. import java.nio.charset.Charset;
  19. import java.util.Objects;

  20. /**
  21.  * Enumerates standard line separators: {@link #CR}, {@link #CRLF}, {@link #LF}.
  22.  *
  23.  * @since 2.9.0
  24.  */
  25. public enum StandardLineSeparator {

  26.     /**
  27.      * Carriage return. This is the line ending used on macOS 9 and earlier.
  28.      */
  29.     CR("\r"),

  30.     /**
  31.      * Carriage return followed by line feed. This is the line ending used on Windows.
  32.      */
  33.     CRLF("\r\n"),

  34.     /**
  35.      * Line feed. This is the line ending used on Linux and macOS X and later.
  36.      */
  37.     LF("\n");

  38.     private final String lineSeparator;

  39.     /**
  40.      * Constructs a new instance for a non-null line separator.
  41.      *
  42.      * @param lineSeparator a non-null line separator.
  43.      */
  44.     StandardLineSeparator(final String lineSeparator) {
  45.         this.lineSeparator = Objects.requireNonNull(lineSeparator, "lineSeparator");
  46.     }

  47.     /**
  48.      * Gets the bytes for this instance encoded using the given Charset.
  49.      *
  50.      * @param charset the encoding Charset.
  51.      * @return the bytes for this instance encoded using the given Charset.
  52.      */
  53.     public byte[] getBytes(final Charset charset) {
  54.         return lineSeparator.getBytes(charset);
  55.     }

  56.     /**
  57.      * Gets the String value of this instance.
  58.      *
  59.      * @return the String value of this instance.
  60.      */
  61.     public String getString() {
  62.         return lineSeparator;
  63.     }
  64. }