Example usage for java.io FileWriter write

List of usage examples for java.io FileWriter write

Introduction

In this page you can find the example usage for java.io FileWriter write.

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:com.smash.revolance.ui.database.FileSystemStorage.java

@Override
public void store(String k, String o, boolean override) throws StorageException {
    if (isKeyValid(k) && (override || !isKeyUsed(k))) {
        FileWriter writer = null;
        File f = new File(databaseFolder, k);
        try {//  w w w.  j a va 2  s  . com
            f.createNewFile();
            writer = new FileWriter(f);
            writer.write(o);

            writer.close();
        } catch (IOException e) {
            throw new StorageException("Unable to create file: " + f + " or to write data into it.");
        } finally {
            IOUtils.closeQuietly(writer);
        }
    } else {
        throw new StorageException("Invalid or already used key: '" + k + "'.");
    }
}

From source file:com.googlecode.fascinator.transformer.basicVersioning.BasicVersioningTransformer.java

private void createVersionIndex(String rootPath) {
    String jsonPath = rootPath + "/" + "Version_Index.json";
    log.debug("Indexing a version into: " + jsonPath);

    JSONArray jArr = null;//from  w  w w  . java  2  s . co m
    try {
        File oldf = new File(jsonPath);
        if (oldf.exists()) {
            log.debug("Need to update a version index file: " + jsonPath);
            JsonSimple js = new JsonSimple(oldf);
            jArr = js.getJsonArray();
        } else {
            log.debug("Need to create a new version index file: " + jsonPath);
            jArr = new JSONArray();
        }
        JsonObject newVer = new JsonObject();
        newVer.put("timestamp", getTimestamp());
        newVer.put("file_name", payloadName());
        try {
            jArr.add(newVer);
            try {
                FileWriter fw = new FileWriter(jsonPath);
                fw.write(jArr.toJSONString());
                fw.flush();
                fw.close();
            } catch (IOException e) {
                log.error("Failed to save versioning property file.", e);
            }
        } catch (Exception eStrange) {
            log.error("Failed to add a new version.", eStrange);
        }
    } catch (Exception eOther) {
        log.error("Failed to create/edit versioning property file.", eOther);
    }
}

From source file:com.consol.citrus.admin.service.spring.SpringBeanServiceTest.java

/**
 * Creates a temporary file in operating system and writes template content to file.
 * @param templateName/* w ww . java 2  s.  c  o m*/
 * @return
 */
private File createTempContextFile(String templateName) throws IOException {
    FileWriter writer = null;
    File tempFile;

    try {
        tempFile = File.createTempFile(templateName, ".xml");

        writer = new FileWriter(tempFile);
        writer.write(
                FileUtils.readToString(new ClassPathResource(templateName + ".xml", SpringBeanService.class)));
    } finally {
        if (writer != null) {
            writer.flush();
            writer.close();
        }
    }

    return tempFile;
}

From source file:com.googlecode.fascinator.transformer.basicVersioning.ExtensionBasicVersioningTransformer.java

private void createVersionIndex(String rootPath, String payloadName, String source) {
    String jsonPath = rootPath + "/" + FilenameUtils.getExtension(source) + "_Version_Index.json";
    log.debug("Indexing a version into: " + jsonPath);

    JSONArray jArr = null;/*  w  w w  .ja va2 s.c  o m*/
    try {
        File oldf = new File(jsonPath);
        if (oldf.exists()) {
            log.debug("Need to update a version index file: " + jsonPath);
            JsonSimple js = new JsonSimple(oldf);
            jArr = js.getJsonArray();
        } else {
            log.debug("Need to create a new version index file: " + jsonPath);
            jArr = new JSONArray();
        }
        // since the transformer is firing off multiple times, as seen from the logs, we need to check if there's a version recorded already...
        String timestamp = getTimestamp();
        for (Object curEntryObj : jArr) {
            JsonObject curEntry = (JsonObject) curEntryObj;
            String curTs = (String) curEntry.get("timestamp");
            if (timestamp.equalsIgnoreCase(curTs)) {
                log.debug("A duplicate of the timestamp " + timestamp
                        + " is already found in the version index, ignoring.");
                return;
            }
        }
        JsonObject newVer = new JsonObject();
        newVer.put("timestamp", timestamp);
        newVer.put("file_name", payloadName); // adding the payloadName as a parameter in the event that calls between payloadname() takes too long
        try {
            jArr.add(newVer);
            try {
                FileWriter fw = new FileWriter(jsonPath);
                fw.write(jArr.toJSONString());
                fw.flush();
                fw.close();
            } catch (IOException e) {
                log.error("Failed to save versioning property file.", e);
            }
        } catch (Exception eStrange) {
            log.error("Failed to add a new version.", eStrange);
        }
    } catch (Exception eOther) {
        log.error("Failed to create/edit versioning property file.", eOther);
    }
}

From source file:com.kk.dic.action.Upload.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    out = response.getWriter();/*  ww  w.  j a v  a 2 s . c o  m*/
    Connection con;
    PreparedStatement pstm = null;
    String fname = "";
    String keyword = "";
    String cd = "";
    String a = (String) request.getSession().getAttribute("email");
    System.out.println("User Name : " + a);
    try {
        boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
        if (!isMultipartContent) {
            return;
        }
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        out.print("one");
        try {
            List<FileItem> fields = upload.parseRequest(request);
            Iterator<FileItem> it = fields.iterator();
            if (!it.hasNext()) {
                return;
            }

            while (it.hasNext()) {
                FileItem fileItem = it.next();
                if (fileItem.getFieldName().equals("name")) {
                    fname = fileItem.getString();
                    System.out.println("File Name" + fname);
                } else if (fileItem.getFieldName().equals("keyword")) {
                    keyword = fileItem.getString();
                    System.out.println("File Keyword" + keyword);
                } else {

                }
                boolean isFormField = fileItem.isFormField();
                if (isFormField) {
                } else {
                    out.print("one");
                    try {
                        con = Dbconnection.getConnection();
                        pstm = con.prepareStatement(
                                "insert into files (file, keyword, filetype, filename, CDate, owner, size, data, frank, file_key)values(?,?,?,?,?,?,?,?,?,?)");
                        out.println("getD " + fileItem.getName());
                        String str = getStringFromInputStream(fileItem.getInputStream());
                        // secretkey generating
                        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
                        keyGen.init(128);
                        SecretKey secretKey = keyGen.generateKey();
                        System.out.println("secret key:" + secretKey);
                        //converting secretkey to String
                        byte[] be = secretKey.getEncoded();//encoding secretkey
                        String skey = Base64.encode(be);
                        System.out.println("converted secretkey to string:" + skey);
                        String cipher = new encryption().encrypt(str, secretKey);
                        System.out.println(str);
                        //for get extension from given file
                        String b = fileItem.getName().substring(fileItem.getName().lastIndexOf('.'));
                        System.out.println("File Extension" + b);
                        pstm.setBinaryStream(1, fileItem.getInputStream());
                        pstm.setString(2, keyword);
                        pstm.setString(3, b);
                        pstm.setString(4, fname);
                        pstm.setDate(5, getCurrentDate());
                        pstm.setString(6, a);
                        pstm.setLong(7, fileItem.getSize());
                        pstm.setString(8, cipher);
                        pstm.setString(9, "0");
                        pstm.setString(10, skey);
                        /*Cloud Start*/
                        File f = new File("D:/" + fileItem.getName());
                        out.print("<br/>" + f.getName());
                        FileWriter fw = new FileWriter(f);
                        fw.write(cipher);
                        fw.close();
                        Ftpcon ftpcon = new Ftpcon();
                        ftpcon.upload(f, fname);
                        /*Cloud End*/
                        int i = pstm.executeUpdate();
                        if (i == 1) {
                            response.sendRedirect("upload.jsp?msg=success");
                        } else {
                            response.sendRedirect("upload.jsp?msgg=failed");
                        }
                        con.close();
                    } catch (Exception e) {
                        out.println(e);
                    }
                }
            }
        } catch (Exception ex) {
            out.print(ex);
            Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
        }
    } finally {
        out.close();
    }
}

From source file:ZipTransformTest.java

public void testFileZipEntryTransformerInStream() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File file1 = File.createTempFile("temp", null);
    File file2 = File.createTempFile("temp", null);
    try {/*from   ww w  .j a  va2 s  .co m*/
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file1));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        // Transform the ZIP file
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(file1);
            out = new FileOutputStream(file2);

            ZipUtil.transformEntry(in, name, new FileZipEntryTransformer() {
                protected void transform(ZipEntry zipEntry, File in, File out) throws IOException {
                    FileWriter fw = new FileWriter(out);
                    fw.write("CAFEBABE");
                    fw.close();
                }
            }, out);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }

        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(file2, name);
        assertNotNull(actual);
        assertEquals("CAFEBABE", new String(actual));
    } finally {
        FileUtils.deleteQuietly(file1);
        FileUtils.deleteQuietly(file2);
    }
}

From source file:de.uzk.hki.da.grid.CTIrodsFacade.java

private File createTestFile() throws IOException {

    new File(tmpDir).mkdir();
    File temp = new File(tmpDir + "urn.tar");
    FileWriter writer = new FileWriter(temp, false);
    writer.write("Hallo Wie gehts?");
    writer.close();/*from w ww.  j av  a  2 s. c  o m*/

    return temp;
}

From source file:com.l2jfree.gameserver.instancemanager.leaderboards.ArenaManager.java

public void saveData() {
    String pattern = "";

    for (Integer object : _ranks.keySet()) {
        ArenaRank ar = _ranks.get(object);

        pattern += object + " : " + ar.kills + "-" + ar.death + " : " + ar.name + "\n";
    }//from  ww  w  .  java  2 s.  co m

    File file = new File(Config.DATAPACK_ROOT, "data/arena.dat");
    try {
        FileWriter fw = new FileWriter(file);

        fw.write("# ownerId : kills-death-name\n");
        fw.write("# ===============================\n\n");
        fw.write(pattern);

        fw.flush();
        fw.close();
    } catch (IOException e) {
        _log.warn("", e);
    }
}

From source file:com.l2jfree.gameserver.instancemanager.leaderboards.FishermanManager.java

public void saveData() {
    String pattern = "";

    for (Integer object : _ranks.keySet()) {
        FishRank ar = _ranks.get(object);

        pattern += object + " : " + ar.cought + "-" + ar.escaped + " : " + ar.name + "\n";
    }/*from  ww w  .  ja  v  a 2 s .c om*/

    File file = new File(Config.DATAPACK_ROOT, "data/fish.dat");
    try {
        FileWriter fw = new FileWriter(file);

        fw.write("# ownerId : cought-escaped-name\n");
        fw.write("# ===============================\n\n");
        fw.write(pattern);

        fw.flush();
        fw.close();
    } catch (IOException e) {
        _log.warn("", e);
    }
}

From source file:de.uzk.hki.da.grid.CTIrodsFacade.java

/**
 * Destroy checksum in Long term storage and verify
 * that grid facade diagnoses it as not valid.
 * /*  w  ww .j  a  v  a 2 s  .  c  om*/
 * @author Jens Peters
 * @author Daniel M. de Oliveira
        
@Test
public void destroyChecksumInStorage() throws Exception {
           
   putFileAndWaitUntilReplicatedAccordingToStoragePolicy();
   assertTrue(ig.isValid(testColl + "/urn.tar"));
   destroyTestFileOnLongTermStorage();
   assertFalse(ig.isValid(testColl + "/urn.tar"));
}
 */
//-----------------------------------------------------------------

private void destroyTestFileOnLongTermStorage() throws IOException {
    File testFile = new File(testCollPhysicalPathOnLTA + "/urn.tar");
    FileWriter writer = new FileWriter(testFile, false);
    writer.write("Hallo Wie gehts? DESTROYED");
    writer.close();
}