[JAVA] Collect line feed codes with enum

Introduction

When outputting the processing result of the program to a file, it may be necessary to specify a line feed code other than the default line feed code of the execution environment. Processing that specifies symbols such as "LF" and "CRLF" in command line parameters and property files, and assigns them to line feed character strings "\ n" and "\ n \ r" according to the specified symbols in the received program I was writing, but I noticed that it was put together in an enum.

Implemented enum NewLine

enum default valueOf (String name) method, if there is no corresponding name specified

java.lang.IllegalArgumentException: No enum constant NewLine.XXX

Since an exception like this is thrown, I prepared a get (String name) method.

NewLine.java


public enum NewLine {
	CR("\r"),
	LF("\n"),
	CRLF("\r\n"),
	DEFAULT(System.lineSeparator());

	private final String value;
	
	private NewLine(String value) {
		this.value = value;
	}

	public String getValue() {
		return value;
	}

	static NewLine get(String name) {
		try {
			return valueOf(name);
		}
		catch (IllegalArgumentException | NullPointerException ignore) {}
		return DEFAULT;
	}
}

Example of use

This is an image that specifies a line break as a property. This is a sample that specifies one of the NewLine enums in the property and uses it in the write method of Writer.

NewLineTest.java


public class NewLineTest {
	
	static Properties prop;
	
	@BeforeClass
	static public void init() {
		prop = new Properties();
		prop.setProperty("newline", "LF");
	}

	@Test
	public void test() throws Exception {
		
		NewLine EOL = NewLine.get(prop.getProperty("newline"));
		
		StringWriter writer = new StringWriter();
		writer.write("line");
		writer.write(EOL.getValue());
		
		System.out.print(writer);
	}
}

Recommended Posts

Collect line feed codes with enum
Convert line feed code to html line feed tag with Thymeleaf and output