Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2006-2007 the original author or authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.springframework.batch.item.file;
 
 import java.io.File;
 import java.io.Writer;
 import java.util.List;
 
This class is an item writer that writes data to a file or stream. The writer also provides restart. The location of the output file is defined by a org.springframework.core.io.Resource and must represent a writable file.
Uses buffered writer to improve performance.
The implementation is *not* thread-safe.

Author(s):
Waseem Malik
Tomas Slanina
Robert Kasanicky
Dave Syer
 
 
 	private static final boolean DEFAULT_TRANSACTIONAL = true;
 
 	protected static final Log logger = LogFactory.getLog(JdbcBatchItemWriter.class);
 
 	private static final String DEFAULT_LINE_SEPARATOR = System.getProperty("line.separator");
 
 	private static final String WRITTEN_STATISTICS_NAME = "written";
 
 	private static final String RESTART_DATA_NAME = "current.count";
 
 	private Resource resource;
 
 	private OutputState state = null;
 
 
 	private boolean saveState = true;
 
 	private boolean shouldDeleteIfExists = true;
 
 	private boolean shouldDeleteIfEmpty = false;
 
 
 
 
 	
 	private boolean transactional = ;
 
 	public FlatFileItemWriter() {
 	}

Assert that mandatory properties (lineAggregator) are set.

	public void afterPropertiesSet() throws Exception {
		Assert.notNull("A LineAggregator must be provided.");
	}

Public setter for the line separator. Defaults to the System property line.separator.

Parameters:
lineSeparator the line separator to set
	public void setLineSeparator(String lineSeparator) {
		this. = lineSeparator;
	}

Public setter for the org.springframework.batch.item.file.transform.LineAggregator. This will be used to translate the item into a line for output.

	public void setLineAggregator(LineAggregator<T> lineAggregator) {
		this. = lineAggregator;
	}

Setter for resource. Represents a file that can be written.

Parameters:
resource
	public void setResource(Resource resource) {
		this. = resource;
	}

Sets encoding for output template.
	public void setEncoding(String newEncoding) {
		this. = newEncoding;
	}

Flag to indicate that the target file should be deleted if it already exists, otherwise it will be appended. If headers are emitted then appending will cause them to show up in the middle of the file. Defaults to true (so no appending except on restart).

Parameters:
shouldDeleteIfExists the flag value to set
	public void setShouldDeleteIfExists(boolean shouldDeleteIfExists) {
		this. = shouldDeleteIfExists;
	}

Flag to indicate that the target file should be deleted if no lines have been written (other than header and footer) on close. Defaults to false.

Parameters:
shouldDeleteIfEmpty the flag value to set
	public void setShouldDeleteIfEmpty(boolean shouldDeleteIfEmpty) {
		this. = shouldDeleteIfEmpty;
	}

Set the flag indicating whether or not state should be saved in the provided org.springframework.batch.item.ExecutionContext during the org.springframework.batch.item.ItemStream call to update. Setting this to false means that it will always start at the beginning on a restart.

Parameters:
saveState
	public void setSaveState(boolean saveState) {
		this. = saveState;
	}

headerCallback will be called before writing the first item to file. Newline will be automatically appended after the header is written.
	public void setHeaderCallback(FlatFileHeaderCallback headerCallback) {
		this. = headerCallback;
	}

footerCallback will be called after writing the last item to file, but before the file is closed.
	public void setFooterCallback(FlatFileFooterCallback footerCallback) {
		this. = footerCallback;
	}

Flag to indicate that writing to the buffer should be delayed if a transaction is active. Defaults to true.
	public void setTransactional(boolean transactional) {
		this. = transactional;
	}

Writes out a string followed by a "new line", where the format of the new line separator is determined by the underlying operating system. If the input is not a String and a converter is available the converter will be applied and then this method recursively called with the result. If the input is an array or collection each value will be written to a separate line (recursively calling this method for each value). If no converter is supplied the input object's toString method will be used.

Parameters:
items list of items to be written to output stream
Throws:
java.lang.Exception if the transformer or file output fail, WriterNotOpenException if the writer has not been initialized.
	public void write(List<? extends T> itemsthrows Exception {
			throw new WriterNotOpenException("Writer must be open before it can be written to");
		}
			.debug("Writing to flat file with " + items.size() + " items.");
		}
		StringBuilder lines = new StringBuilder();
		int lineCount = 0;
		for (T item : items) {
			lineCount++;
		}
		try {
			state.write(lines.toString());
		}
		catch (IOException e) {
			throw new WriteFailedException("Could not write data.  The file may be corrupt."e);
		}
		state.linesWritten += lineCount;
	}

	public void close() {
		if ( != null) {
			try {
				if ( != null && . != null) {
				}
			}
			catch (IOException e) {
				throw new ItemStreamException("Failed to write footer before closing"e);
			}
			finally {
					try {
					}
					catch (IOException e) {
						throw new ItemStreamException("Failed to delete empty file on close"e);
					}
				}
				 = null;
			}
		}
	}

Initialize the reader. This method may be called multiple times before close is called.

	public void open(ExecutionContext executionContextthrows ItemStreamException {
		Assert.notNull("The resource must be set");
			doOpen(executionContext);
		}
	}
	private void doOpen(ExecutionContext executionContextthrows ItemStreamException {
		OutputState outputState = getOutputState();
		if (executionContext.containsKey(getKey())) {
			outputState.restoreFrom(executionContext);
		}
		try {
		}
		catch (IOException ioe) {
			throw new ItemStreamException("Failed to initialize writer"ioe);
		}
		if (outputState.lastMarkedByteOffsetPosition == 0) {
			if ( != null) {
				try {
					.writeHeader(outputState.outputBufferedWriter);
					outputState.write();
				}
				catch (IOException e) {
					throw new ItemStreamException("Could not write headers.  The file may be corrupt."e);
				}
			}
		}
	}

	public void update(ExecutionContext executionContext) {
		if ( == null) {
			throw new ItemStreamException("ItemStream not open or already closed.");
		}
		Assert.notNull(executionContext"ExecutionContext must not be null");
		if () {
			try {
			}
			catch (IOException e) {
				throw new ItemStreamException("ItemStream does not return current position properly"e);
			}
		}
	}
	// Returns object representing state.
		if ( == null) {
			File file;
			try {
				file = .getFile();
			}
			catch (IOException e) {
				throw new ItemStreamException("Could not convert resource to file: [" +  + "]"e);
			}
			Assert.state(!file.exists() || file.canWrite(), "Resource is not writable: [" +  + "]");
			 = new OutputState();
		}
		return (OutputState;
	}

Encapsulates the runtime state of the writer. All state changing operations on the writer go through this class.
	private class OutputState {
		// default encoding for writing to output files - set to UTF-8.
		private static final String DEFAULT_CHARSET = "UTF-8";
		// The bufferedWriter over the file channel that is actually written
		// this represents the charset encoding (if any is needed) for the
		// output file
		boolean restarted = false;
		long linesWritten = 0;
		boolean shouldDeleteIfExists = true;
		boolean initialized = false;

Return the byte offset position of the cursor in the output file as a long integer.
		public long position() throws IOException {
			long pos = 0;
			if ( == null) {
				return 0;
			}
			}
			return pos;
		}

Parameters:
executionContext
		public void restoreFrom(ExecutionContext executionContext) {
			 = true;
		}

Parameters:
shouldDeleteIfExists
		public void setDeleteIfExists(boolean shouldDeleteIfExists) {
			this. = shouldDeleteIfExists;
		}

Parameters:
encoding
		public void setEncoding(String encoding) {
			this. = encoding;
		}

Close the open resource and reset counters.
		public void close() {
			 = false;
			 = false;
			try {
				if ( != null) {
				}
			}
			catch (IOException ioe) {
				throw new ItemStreamException("Unable to close the the ItemWriter"ioe);
			}
			finally {
				if (!) {
				}
			}
		}
		private void closeStream() {
			try {
				if ( != null) {
				}
			}
			catch (IOException ioe) {
				throw new ItemStreamException("Unable to close the the ItemWriter"ioe);
			}
			finally {
				try {
					if ( != null) {
					}
				}
				catch (IOException ioe) {
					throw new ItemStreamException("Unable to close the the ItemWriter"ioe);
				}
			}
		}

Parameters:
line
Throws:
java.io.IOException
		public void write(String linethrows IOException {
			if (!) {
			}
		}

Truncate the output at the last known good point.

		public void truncate() throws IOException {
		}

Creates the buffered writer for the output file channel based on configuration information.

		private void initializeBufferedWriter() throws IOException {
			File file = .getFile();
			 = new FileOutputStream(file.getAbsolutePath(), true);
			Assert.state( != null);
			// in case of restarting reset position to last committed point
			if () {
			}
			 = true;
		}
		public boolean isInitialized() {
			return ;
		}

Returns the buffered writer opened to the beginning of the file specified by the absolute path name contained in absoluteFileName.
		private Writer getBufferedWriter(FileChannel fileChannelString encoding) {
			try {
				Writer writer = Channels.newWriter(fileChannelencoding);
					return new TransactionAwareBufferedWriter(writernew Runnable() {
						public void run() {
						}
					});
else {
					return new BufferedWriter(writer);
				}
			}
				throw new ItemStreamException("Bad encoding configuration for output file " + fileChannelucse);
			}
		}

Checks (on setState) to make sure that the current output file's size is not smaller than the last saved commit point. If it is, then the file has been damaged in some way and whole task must be started over again from the beginning.

Throws:
java.io.IOException if there is an IO problem
		private void checkFileSize() throws IOException {
			long size = -1;
			size = .size();
				throw new ItemStreamException("Current file size is smaller than size at last commit");
			}
		}
	}
New to GrepCode? Check out our FAQ X