List of usage examples for org.apache.commons.io IOUtils write
public static void write(StringBuffer data, OutputStream output, String encoding) throws IOException
StringBuffer
to bytes on an OutputStream
using the specified character encoding. From source file:ch.cyberduck.core.serializer.impl.dd.PlistWriter.java
@Override public void write(final Collection<S> collection, final Local file) throws AccessDeniedException { final NSArray list = new NSArray(collection.size()); int i = 0;/*from w w w. j a va 2 s . c o m*/ for (S bookmark : collection) { list.setValue(i, bookmark.<NSDictionary>serialize(SerializerFactory.get())); i++; } final String content = list.toXMLPropertyList(); final OutputStream out = file.getOutputStream(false); try { IOUtils.write(content, out, Charset.forName("UTF-8")); } catch (IOException e) { throw new AccessDeniedException(String.format("Cannot create file %s", file.getAbsolute()), e); } finally { IOUtils.closeQuietly(out); } }
From source file:com.thoughtworks.go.config.GoConfigFileWriter.java
public synchronized void writeToConfigXmlFile(String content) { FileChannel channel = null;// w ww. j a v a 2 s . com FileOutputStream outputStream = null; FileLock lock = null; try { RandomAccessFile randomAccessFile = new RandomAccessFile(fileLocation(), "rw"); channel = randomAccessFile.getChannel(); lock = channel.lock(); randomAccessFile.seek(0); randomAccessFile.setLength(0); outputStream = new FileOutputStream(randomAccessFile.getFD()); IOUtils.write(content, outputStream, UTF_8); } catch (Exception e) { throw new RuntimeException(e); } finally { if (channel != null && lock != null) { try { lock.release(); channel.close(); IOUtils.closeQuietly(outputStream); } catch (IOException e) { LOGGER.error("Error occured when releasing file lock and closing file.", e); } } } }
From source file:jp.igapyon.diary.v3.util.IgapyonV3Util.java
/** * Write html file.//from w w w.j a v a 2 s. co m * * @param strHtml * @param file * @throws IOException */ public static void writeHtmlFile(final String strHtml, final File file) throws IOException { final FileOutputStream outStream = new FileOutputStream(file); try { IOUtils.write(strHtml, outStream, "UTF-8"); outStream.flush(); } finally { IOUtils.closeQuietly(outStream); } }
From source file:com.fizzed.rocker.reload.ReloadTest.java
@Test public void reload() throws Exception { // render initial String out = Rocker.template("views/index.rocker.html", "Home", "Joe").render().toString(); assertThat(out, containsString("<h1>Hi, Joe!</h1>")); // to find path reliably of source file, we'll take something on classpath // for this project and then do something relative to it URL logbackUrl = ReloadTest.class.getResource("/logback.xml"); File projectDir = new File(logbackUrl.toURI()).getParentFile().getParentFile().getParentFile(); File currentTemplateFile = new File(projectDir, "src/test/java/views/index.rocker.html"); FileInputStream fis = new FileInputStream(currentTemplateFile); String currentTemplate = IOUtils.toString(fis, "UTF-8"); String newTemplate = currentTemplate.replace("<h1>Hi, @name!</h1>", "<h1>Hi, @name!?!</h1>"); try {/*from ww w. j a v a 2 s . co m*/ FileOutputStream fos = new FileOutputStream(currentTemplateFile); IOUtils.write(newTemplate, fos, "UTF-8"); out = Rocker.template("views/index.rocker.html", "Home", "Joe").render().toString(); assertThat(out, containsString("<h1>Hi, Joe!?!</h1>")); } finally { // restore template back... FileOutputStream fos = new FileOutputStream(currentTemplateFile); IOUtils.write(currentTemplate, fos, "UTF-8"); } // since we base reloading on timestamp, need to force something // different since these tests run so quickly currentTemplateFile.setLastModified(System.currentTimeMillis() + 5000); // try the restored file one more time out = Rocker.template("views/index.rocker.html", "Home", "Joe").render().toString(); assertThat(out, containsString("<h1>Hi, Joe!</h1>")); }
From source file:com.igormaznitsa.nbmindmap.nb.refactoring.elements.AbstractElement.java
protected static void writeMindMap(final File file, final MindMap map) throws IOException { final FileObject fileObject = FileUtil.toFileObject(file); FileLock lock = null;/* w w w. j av a2 s . c o m*/ while (true) { try { lock = fileObject.lock(); break; } catch (FileAlreadyLockedException ex) { delay(500L); } } try { final OutputStream out = fileObject.getOutputStream(lock); try { IOUtils.write(map.packToString(), out, "UTF-8"); //NOI18N } finally { IOUtils.closeQuietly(out); } } finally { if (lock != null) { lock.releaseLock(); } } }
From source file:com.scaleunlimited.cascading.DatumCompilerTest.java
@Test public void testSimpleSchema() throws Exception { CompiledDatum result = DatumCompiler.generate(MyDatumTemplate.class); File baseDir = new File("build/test/DatumCompilerTest/testSimpleSchema/"); FileUtils.deleteDirectory(baseDir);// w ww. j a v a 2s .c om File srcDir = new File(baseDir, result.getPackageName().replaceAll("\\.", "/")); assertTrue(srcDir.mkdirs()); File codeFile = new File(srcDir, result.getClassName() + ".java"); OutputStream os = new FileOutputStream(codeFile); IOUtils.write(result.getClassCode(), os, "UTF-8"); os.close(); // Compile with Janino, give it a try. We have Janino since // it's a cascading dependency, but probably want to add a test // dependency on it. ClassLoader cl = new JavaSourceClassLoader(this.getClass().getClassLoader(), // parentClassLoader new File[] { baseDir }, // optionalSourcePath (String) null // optionalCharacterEncoding ); // WARNING - we have to use xxxDatumTemplate as the base name, so that the code returned // by the compiler is for type xxxDatum. Otherwise when we try to load the class here, // we'll likely get the base (template) class, which will mask our generated class. Class clazz = cl.loadClass(result.getPackageName() + "." + result.getClassName()); assertEquals("MyDatum", clazz.getSimpleName()); // Verify that we have a constructor which takes all of the fields. // private String _name; // private int ageAndRisk; // private Date _date; // private Tuple _aliases; // private String[] _phoneNumbers // private MyDatumEnum _enum Constructor c = clazz.getConstructor(String.class, int.class, Date.class, Tuple.class, String[].class, MyDatumEnum.class); BaseDatum datum = (BaseDatum) c.newInstance("robert", 25, new Date(), new Tuple("bob", "rob"), new String[] { "555-1212", "555-4848" }, MyDatumEnum.DATUM_COMPILER_ENUM_2); // Verify that it can be serialized with Hadoop. // TODO figure out why Hadoop serializations aren't available??? /* BasePlatform testPlatform = new HadoopPlatform(DatumCompilerTest.class); Tap tap = testPlatform.makeTap( testPlatform.makeBinaryScheme(datum.getFields()), testPlatform.makePath("build/test/DatumCompilerTest/testSimpleSchema/")); TupleEntryCollector writer = tap.openForWrite(testPlatform.makeFlowProcess()); writer.add(datum.getTuple()); writer.close(); TupleEntryIterator iter = tap.openForRead(testPlatform.makeFlowProcess()); TupleEntry te = iter.next(); // TODO how to test round-trip? */ }
From source file:com.twinsoft.convertigo.engine.admin.services.roles.Export.java
@Override protected void writeResponseResult(HttpServletRequest request, HttpServletResponse response) throws Exception { //We recover selected users String users = "{ users : [" + request.getParameter("users") + "] }"; if (users != null && !users.equals("")) { //Parse string requested parameter to JSON JSONObject jsonObj = new JSONObject(users); JSONArray usernames = jsonObj.getJSONArray("users"); JSONObject export = Engine.authenticatedSessionManager.exportUsers(usernames); HeaderName.ContentDisposition.setHeader(response, "attachment; filename=\"user_roles.json\""); response.setContentType(MimeType.Plain.value()); IOUtils.write(export.toString(2), response.getOutputStream(), "UTF-8"); String message = "The users file has been exported."; Engine.logAdmin.info(message);//from w w w . j a va2s . c o m } else { String message = "Error when parsing the requested parameter!"; Engine.logAdmin.error(message); throw new Exception("Error when parsing the requested parameter!"); } }
From source file:ch.cyberduck.core.serializer.impl.dd.PlistWriter.java
@Override public void write(final S item, final Local file) throws AccessDeniedException { final String content = item.<NSDictionary>serialize(SerializerFactory.get()).toXMLPropertyList(); final OutputStream out = file.getOutputStream(false); try {//from w w w.j av a 2 s.c om IOUtils.write(content, out, Charset.forName("UTF-8")); } catch (IOException e) { throw new AccessDeniedException(String.format("Cannot create file %s", file.getAbsolute()), e); } finally { IOUtils.closeQuietly(out); } }
From source file:com.adaptris.core.common.FileDataOutputParameter.java
@Override public void insert(String data, InterlokMessage message) throws CoreException { try {/*from w ww. jav a2 s . c o m*/ URL url = FsHelper.createUrlFromString(this.url(message), true); try (OutputStream out = new FileOutputStream(FsHelper.createFileReference(url))) { IOUtils.write((String) data, out, message.getContentEncoding()); } } catch (Exception e) { throw ExceptionHelper.wrapCoreException(e); } }
From source file:fr.litarvan.commons.config.JSONConfig.java
@Override public FileConfig save() { try {/*from w ww. j a v a 2s . c om*/ IOUtils.write(gson.toJson(config), file.provideOutput(), Charset.defaultCharset()); } catch (IOException e) { throw new RuntimeException("Can't save the config", e); } return this; }