ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Samples] - PropertiesFileWriter
    Java/Samples 2016. 5. 24. 11:33
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.Writer;
    import java.util.Map.Entry;
    import java.util.Properties;
    
    public class PropertiesFileWriter extends BufferedWriter {
    	private static final String EXTENSION = "properties";
    	private static final String COMMENT_HEADER = "#";
    	
    	private PropertiesFileWriter(Writer out) throws IOException {
    		super(out);
    	}
    	
    	public PropertiesFileWriter(File file) throws IOException, IllegalArgumentException {
    		this(new FileWriter(file, false));
    	}
    	
    	public PropertiesFileWriter(File file, boolean append) throws IOException, IllegalArgumentException {
    		this(new FileWriter(file, append));
    		
    		if (!file.getPath().endsWith(EXTENSION)) {
    			throw new IllegalArgumentException("Invalid file extension.");
    		}
    	}
    	
    	/**
    	 * 주석을 추가하고 개행
    	 * @param comment
    	 * @return
    	 * @throws IOException
    	 */
    	public PropertiesFileWriter commentln(CharSequence comment) throws IOException {
    		appendln(COMMENT_HEADER + comment);
    		return this;
    	}
    	
    	/**
    	 * 내용을 추가하고 개행
    	 * @param val
    	 * @return
    	 * @throws IOException
    	 */
    	public PropertiesFileWriter appendln(CharSequence val) throws IOException {
    		append(val);
    		newLine();
    		return this;
    	}
    	
    	/**
    	 * 내용을 추가하고 개행
    	 * @param val
    	 * @return
    	 * @throws IOException
    	 */
    	public PropertiesFileWriter writeln(String val) throws IOException {
    		write(val);
    		newLine();
    		return this;
    	}
    	
    	public PropertiesFileWriter writeln(String key, String value) throws IOException {
    		write(String.format("%s=%s", key, value));
    		newLine();
    		return this;
    	}
    	
    	/**
    	 * 프로퍼티 내용을 추가하고 개행
    	 * @param properties
    	 * @return
    	 * @throws IOException
    	 */
    	public PropertiesFileWriter writeln(Properties properties) throws IOException {
    		for(Entry<Object, Object> entry : properties.entrySet()) {
    			String key = (String) entry.getKey();
    			String value = (String) entry.getValue();
    			writeln(String.format("%s=%s", key, value));
    		}
    		return this;
    	}
    	
    	/**
    	 * 주석을 달고 프로퍼티 내용을 추가하고 개행
    	 * @param comment
    	 * @param properties
    	 * @return
    	 * @throws IOException
    	 */
    	public PropertiesFileWriter writeln(CharSequence comment, Properties properties) throws IOException {
    		commentln(comment);
    		writeln(properties);
    		return this;
    	}
    }
    
    


    'Java > Samples' 카테고리의 다른 글

    [Samples] - StopWatch  (0) 2015.12.14

    댓글

Designed by Tistory.