Java tutorial
/* Copyright 2014 Wassim Akachi - itmanwuiso.com 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 com.itmanwuiso.checksums.dao; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.List; import org.json.simple.JSONArray; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.itmanwuiso.checksums.HashResult; import com.itmanwuiso.checksums.InvalidArgumentException; public class ResultJSONWriter implements ResultWriter { private static Logger logger = LoggerFactory.getLogger(ResultJSONWriter.class); private Formatter converter; private File file; public ResultJSONWriter() { super(); converter = new Formatter(); } public ResultJSONWriter(File file) { converter = new Formatter(); this.file = file; if (this.file == null) { throw new InvalidArgumentException("File isn't accessable."); } } @SuppressWarnings("unchecked") public boolean write(List<HashResult> resuls, OutputStream outputStream) { if (null == resuls || outputStream == null) { throw new InvalidArgumentException("Resuls or OutputStream is " + "null."); } JSONArray jsons = new JSONArray(); for (HashResult hr : resuls) { jsons.add(converter.resultToJson(hr)); } try { outputStream.write(jsons.toString().getBytes()); outputStream.flush(); outputStream.close(); jsons.clear(); return true; } catch (IOException io) { logger.error("", io); } return false; } public void write(List<HashResult> resuls) { try { write(resuls, new FileOutputStream(file)); } catch (FileNotFoundException e) { logger.error("", e); } } }