Example usage for java.io FileWriter flush

List of usage examples for java.io FileWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:com.meltmedia.cadmium.core.history.HistoryManagerTest.java

@Before
public void setupForTest() throws Exception {
    File testDir = new File("./target/history-test");
    testDirectory = testDir.getAbsoluteFile().getAbsolutePath();

    if (!testDir.exists()) {
        testDir.mkdirs();/*  w ww.j a  v  a2  s  .c om*/
    }

    historyFile = new File(testDir, HistoryManager.HISTORY_FILE_NAME);

    if (!historyFile.exists() || historyFile.canWrite()) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(historyFile, false);
            writer.write(INIT_HISTORY_CONTENT);
            writer.flush();
        } catch (Exception e) {
        } finally {
            IOUtils.closeQuietly(writer);
        }
    }

    manager = new HistoryManager(testDirectory, Executors.newSingleThreadExecutor(), mock(EventQueue.class));
}

From source file:mn.EngineForge.module.player.java

public void saveRegisteration() throws IOException {
    JSONObject reg = new JSONObject();
    reg.put("ID", id);
    reg.put("USERNAME", username);
    reg.put("PASSWORD", password);
    reg.put("REG_DATE", null);
    reg.put("LAST_LOGIN", null);
    reg.put("POSITION", null);
    /* JSON ARRAY NOTE//ww  w .j a va 2 s.  co  m
    JSONArray company = new JSONArray();
    company.add("Compnay: eBay");
    company.add("Compnay: Paypal");
    company.add("Compnay: Google");
    reg.put("Company List", company);
    */
    FileWriter file = new FileWriter(this.path);
    try {
        file.write(reg.toJSONString());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        file.flush();
        file.close();
    }
}

From source file:WebCategorizer.java

private JSONObject fetchCategories() {
    try {/*w w w  . j  ava2s .  co  m*/
        JSONObject webCatList = new JSONObject();
        URL obj = new URL(categoriesUrl);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-agent", "Web Categorizer");
        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            JSONArray inputData = new JSONArray(response.toString());
            for (Object currObj : inputData) {
                JSONObject tempObj = (JSONObject) currObj;
                webCatList.put(String.format("%02X", tempObj.get("num")).toLowerCase(), tempObj.get("name"));
            }

            FileWriter file = new FileWriter(categoriesFile);
            file.write(webCatList.toString());
            file.flush();
            file.close();
        } else {
            System.out.println("Not working");
        }
        return webCatList;
    } catch (Exception ex) {
        return new JSONObject();
    }
}

From source file:gov.nih.nci.caintegrator.domain.application.AbstractPersistedAnalysisJob.java

/**
 * Writes the job description to the given file.
 * @param file to write to./*from w w w  .  jav  a  2  s .c o  m*/
 * @throws IOException if unable to write to file.
 */
public void writeJobDescriptionToFile(File file) throws IOException {
    FileWriter fw = new FileWriter(file);
    fw.append(toString());
    fw.flush();
    fw.close();
}

From source file:bridge.toolkit.commands.PostProcess.java

/**
 * The unit of processing work to be performed for the PostProcess module.
 * @see org.apache.commons.chain.Command#execute(org.apache.commons.chain.Context)
 *//*  w ww .ja  v  a 2  s. c o m*/
@Override
public boolean execute(Context ctx) {
    System.out.println("Executing Post Process");
    if ((ctx.get(Keys.XML_SOURCE) != null) && (ctx.get(Keys.CP_PACKAGE) != null)) {
        File cpPackage = (File) ctx.get(Keys.CP_PACKAGE);

        Document manifest = (Document) ctx.get(Keys.XML_SOURCE);

        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        File temp = new File(cpPackage + File.separator + "imsmanifest.xml");
        try {
            //writes the imsmanfest.xml file out to the content package
            FileWriter writer = new FileWriter(temp, false);
            outputter.output(manifest, writer);
            writer.flush();
            writer.close();

            //copies the required xsd files over to the content package
            CopyDirectory cd = new CopyDirectory();
            //check if the directory exists if it does use it else copy it from the jar
            File xsd_loc = new File(System.getProperty("user.dir") + File.separator + "xsd");
            if (xsd_loc.exists()) {
                cd.copyDirectory(xsd_loc, cpPackage);
            } else {
                cd.CopyJarFiles(this.getClass(), "xsd", cpPackage.getAbsolutePath());
            }
        } catch (java.io.IOException e) {
            System.out.println("Content Package creation was unsuccessful");
            e.printStackTrace();
            return PROCESSING_COMPLETE;
        }

        //get the organization title from the manifest file 
        //replace any white spaces with 
        Element title = null;
        XPath xp = null;
        try {
            xp = XPath.newInstance("//ns:organization//ns:title");
            xp.addNamespace("ns", "http://www.imsglobal.org/xsd/imscp_v1p1");
            title = (Element) xp.selectSingleNode(manifest);
        } catch (JDOMException e) {
            System.out.println("Content Package creation was unsuccessful");
            e.printStackTrace();
            return PROCESSING_COMPLETE;
        }
        String outputPath = "";
        if (ctx.get(Keys.OUTPUT_DIRECTORY) != null) {
            outputPath = (String) ctx.get(Keys.OUTPUT_DIRECTORY);
            if (outputPath.length() > 0) {
                outputPath = outputPath + File.separator;
            }
        }
        File outputDir = new File(outputPath);
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }

        String zipName = title.getValue();
        zipName = zipName.replace(" ", "_").trim();
        zipName = zipName.replace("\n", "").trim();

        File zip = new File(zipName + ".zip");
        if (!outputDir.getName().equals(""))
            zip = new File(outputDir + File.separator + zipName + ".zip");

        ZipCreator zipCreator = new ZipCreator();
        try {
            zipCreator.zipFiles(cpPackage, zip);
        } catch (IOException e) {
            System.out.println("Content Package creation was unsuccessful");
            e.printStackTrace();
            return PROCESSING_COMPLETE;
        }

        cpPackage.deleteOnExit();
        System.out.println("Content Package creation was successful");
    } else {
        System.out.println("Content Package creation was unsuccessful");
        System.out.println("One of the required Context entries for the " + this.getClass().getSimpleName()
                + " command to be executed was null");
        return PROCESSING_COMPLETE;
    }
    return CONTINUE_PROCESSING;
}

From source file:presenter.MainPresenter.java

@Override
public void saveMovementsequenceToFile(ActionEvent e) {
    JFileChooser fc = new JFileChooser();

    if (fc.showSaveDialog((Component) e.getSource()) == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        try {//w ww. j a va 2  s. c  o  m
            FileWriter fw = new FileWriter(file);
            fw.write(this.movSeq.toString());
            fw.flush();
            fw.close();
            this.displayStatus("File was written successfully!");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}

From source file:it.unibas.spicygui.controllo.tree.ActionExportQuery.java

public void actionPerformed(ActionEvent e) {
    this.executeInjection();
    JFileChooser chooser = vista.getFileChooserSalvaFileGenerico();
    File file;//from w  w  w  .j  a  v  a  2s . c  o  m
    int returnVal = chooser.showDialog(WindowManager.getDefault().getMainWindow(),
            NbBundle.getMessage(Costanti.class, Costanti.EXPORT));
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        FileWriter writer = null;
        try {
            file = chooser.getSelectedFile();
            writer = new FileWriter(file);
            writer.write(this.textArea.getText());
            writer.flush();
            StatusDisplayer.getDefault().setStatusText(NbBundle.getMessage(Costanti.class, Costanti.EXPORT_OK));
        } catch (IOException ex) {
            DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
                    NbBundle.getMessage(Costanti.class, Costanti.EXPORT_ERROR) + " : " + ex.getMessage(),
                    DialogDescriptor.ERROR_MESSAGE));
            logger.error(ex);
        } finally {
            try {
                writer.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:org.zalando.stups.swagger.codegen.YamlToJson.java

public void convert() {
    logger.info("Generate .json file from .yaml");

    File outputDirectory = new File(outputDirectoryPath);
    if (!outputDirectory.exists()) {
        outputDirectory.mkdirs();//from   www.  ja va2s.  c o  m
        logger.info("OutputDirectory created");
    }

    File jsonFile = new File(outputDirectory, getYamlFilename() + ".json");
    FileWriter fileWriter = null;
    try {

        fileWriter = new FileWriter(jsonFile);
        fileWriter.write(getYamlFileContentAsJson());
        fileWriter.flush();
        logger.info("File written to " + jsonFile.getAbsolutePath());
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(fileWriter);
    }
}

From source file:forumbox.PostingnewpostServlet.java

public void filewrite(String url, String username, String title, String description,
        HttpServletResponse response, String id) throws IOException {

    count++;//from   w w w . j a  v a2 s.  c o m
    /*   BufferedWriter out ;
       out = new BufferedWriter(new FileWriter(url,true));
       out.write(count+"/"+array[0]+"/"+array[1]+"/"+array[2]+";");
       out.close();
               
               
      }catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
      } */

    JSONObject post = new JSONObject();
    JSONArray comments = new JSONArray();
    JSONArray toapprove = new JSONArray();
    JSONParser parser = new JSONParser();
    JSONObject list = null;

    post.put("title", title);
    post.put("description", description);
    post.put("id", id);
    post.put("username", username);
    //  post.put("comments",comments);
    //  post.put("toapprove",toapprove);

    try {

        Object obj = parser.parse(new FileReader(url + "list.json"));
        list = (JSONObject) obj;

        JSONArray msg = (JSONArray) list.get("list");
        msg.add(id);

        list.remove("list");
        list.put("list", msg);

    } catch (Exception e) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("Adding new ID is unsuccessful");
        out.println(e);
        out.println("......................");
    }

    try {

        File file = new File(url + id + ".json");
        file.createNewFile();
        BufferedWriter out;
        out = new BufferedWriter(new FileWriter(file));
        out.write(post.toJSONString());
        out.close();

        File fileList = new File(url + "list.json");
        //  fileList.createNewFile();
        // BufferedWriter outin ;
        //  outin = new BufferedWriter(new FileWriter(fileList));
        // outin.write(post.toJSONString());
        FileWriter listwrite = new FileWriter(fileList);
        listwrite.write(list.toJSONString());
        listwrite.flush();
        listwrite.close();
        //outin.close();

    } catch (IOException e) {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("adding new post is unsuccessful");
        out.println(e);
        out.println("......................");
    }

}

From source file:com.aionengine.gameserver.dataholders.DataLoader.java

/**
 * Saves data to the file. Used only by {@link SpawnData}.
 *
 * @return true if the data was successfully saved, false - if some error occurred.
 *//*from   w  w w .j  a  va 2s. com*/
public boolean saveData() {
    String desc = PATH + getSaveFile();

    log.info("Saving " + desc);

    FileWriter fr = null;
    try {
        fr = new FileWriter(desc);

        saveEntries(fr);

        fr.flush();

        return true;
    } catch (Exception e) {
        log.fatal("Error while saving " + desc, e);
        return false;
    } finally {
        if (fr != null) {
            try {
                fr.close();
            } catch (Exception e) {
                log.fatal("Error while closing save data file", e);
            }
        }
    }
}