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:JSON.GenererJSONSave.java

/**
 * Methode pour sauvegarder le plateau d'un jeu
 * @param p /*from   w w  w . j  av a 2  s .  c om*/
 */
public void Save(Plateau p) {
    ArrayList<Sauvegarde> Liste = new ArrayList();
    int k = 0;
    for (int i = 0; i < p.getAbsci(); i++) {
        for (int j = 0; j < p.getOrdonne(); j++) {
            if (p.grille[i][j] != null)
                Liste.add(new Sauvegarde(i, j, p.grille[i][j].nom));

        }
    }
    JSONObject objet = new JSONObject();
    JSONArray jsArray = new JSONArray(Liste);
    objet.put("coordonne", jsArray);
    // Cration du fichier de sortie
    FileWriter fs = null;
    try {
        fs = new FileWriter("C:\\Users\\Alphonse\\Desktop\\output2.txt");
    } catch (IOException e) {
        System.err.println("Erreur lors de l'ouverture du fichier ");
        System.err.println(e);
        System.exit(-1);
    }

    // Sauvegarde dans le fichier
    try {
        objet.write(fs);
        fs.flush();
    } catch (IOException e) {
        System.err.println("Erreur lors de l'criture dans le fichier : " + e);
        System.exit(-1);
    }
}

From source file:wsattacker.plugin.dos.dosExtension.result.ResultGenerator.java

private void saveFilelocationToReport(String dateString, String filenameUntampered, String filenameTampered,
        String filenameTestprobe, String filenameMetadata, String filenameImgGraph, String filenameReport,
        String filenameZip, String fullPath) throws IOException {
    // Write Filelocation to report.html-File:
    String htmlString = "" + "<html>"
            + "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head>"
            + "<body>" + "<h1>Attack Report for '" + attackModel.getAttackName() + "' - created: " + dateString
            + "</h1>" + "<p><img src='ok.jpg'/>Attack report generated succesfully</p>"
            + "<p>The attack report is provided in the following files: " + "<ul>" + "<li><a href='"
            + filenameMetadata + "'>Attack Summary</a></li>" + "<li><a href='" + filenameImgGraph
            + "'>Attackgraph via PNG</a></li>" + "<li><a href='" + filenameUntampered
            + "'>CSV-Dataset Untampered-Requests</a></li>" + "<li><a href='" + filenameTampered
            + "'>CSV-Dataset Tampered-Requests</a></li>" + "<li><a href='" + filenameTestprobe
            + "'>CSV-Dataset Testprobe-Requests</a></li>" + "</ul>" + "<p>compressed Version as zip <a href='"
            + filenameZip + "'>results.zip</a></p>" + "</body>" + "</html>";
    File file = new File(fullPath, filenameReport);
    FileWriter writer = new FileWriter(file);
    writer.append(htmlString);//  w w w .j  a  va  2  s  .c  o m
    writer.flush();
    writer.close();
}

From source file:com.ewcms.publication.PublishIntegratedTest.java

private void writerDepender(FileWriter writer, Taskable task, int level) throws IOException {
    String space = SPACE.substring(0, level * 2);
    int progress = task.getProgress();
    if (progress != -1) {
        String info = String.format("%s%s? %d", space, task.getDescription(), progress);
        writer.append(info).append("\n");
        writer.flush();
    }//from w w  w  .  j  av  a 2  s. c  o m
    List<Taskable> children = task.getDependenceTasks();
    level = level + 1;
    for (Taskable child : children) {
        writerDepender(writer, child, level);
    }
    level = level - 1;
}

From source file:gobblin.example.simplejson.SimpleJsonSource.java

@Override
public List<WorkUnit> getWorkunits(SourceState state) {
    List<WorkUnit> workUnits = Lists.newArrayList();

    if (!state.contains(ConfigurationKeys.SOURCE_FILEBASED_FILES_TO_PULL)) {
        return workUnits;
    }/*from  w w  w. ja  v a2s .  c  o  m*/

    // Create a single snapshot-type extract for all files
    Extract extract = new Extract(state, Extract.TableType.SNAPSHOT_ONLY,
            state.getProp(ConfigurationKeys.EXTRACT_NAMESPACE_NAME_KEY, "ExampleNamespace"), "ExampleTable");

    String filesToPull = state.getProp(ConfigurationKeys.SOURCE_FILEBASED_FILES_TO_PULL);
    File tempFileDir = new File("test_temp/"); // TODO: Delete the dir after completion.
    tempFileDir.mkdir();
    String tempFileDirAbsolute = "";
    try {
        tempFileDirAbsolute = tempFileDir.getCanonicalPath(); // Retrieve absolute path of temp folder
    } catch (IOException e) {
        e.printStackTrace();
    }

    int nameCount = 0;
    int csvCount = 0;
    for (String file : Splitter.on(',').omitEmptyStrings().split(filesToPull)) {
        Iterator it = FileUtils.iterateFiles(new File(file), null, true);
        while (it.hasNext()) {
            try {
                File newFile = (File) it.next();
                String basePath = newFile.getCanonicalPath(); // Retrieve absolute path of source
                Path path = newFile.toPath();

                //call to rest api:, provide with file basePath
                String extension = "";
                System.out.println("basePath is" + basePath);
                int i = basePath.lastIndexOf('.');
                System.out.println("i");
                if (i > 0) {
                    extension = basePath.substring(i + 1);
                }

                String url_file_name = "";
                int j = basePath.lastIndexOf('/');
                if (j > 0) {
                    url_file_name = basePath.substring(j + 1);
                }

                //hand off to rest api
                if (extension.equals("csv")) {
                    System.out.println("CSVCSVCSV");
                    csvCount += 1;
                    System.out.println("CURL________________________________________");
                    //Include basePath, filename, location you want to store file
                    System.out.println(
                            "curl http://localhost:8080" + basePath + "/" + Integer.toString(nameCount));
                    //10.0.2.2 is localhost from vagrant
                    // Insert the nameCount so that it can be joined back later.
                    Process p = Runtime.getRuntime()
                            .exec("curl http://localhost:8080" + basePath + "/" + Integer.toString(nameCount));
                    // String myUrl = "http://localhost:8080/parse" + basePath + "&" + url_file_name + "&" + tempFileDirAbsolute;
                    // System.out.println("------------------------------");
                    // System.out.println(myUrl);
                    // try {
                    //   URL url = new URL(myUrl);
                    //   HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    //   connection.setRequestMethod("GET");
                    //   connection.connect();
                    // } catch (Exception e) {
                    //   e.printStackTrace();
                    // }

                }
                // Print filename and associated metadata 
                System.out.println(basePath);
                BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
                // System.out.println("  creationTime: " + attr.creationTime());
                // System.out.println("  lastAccessTime: " + attr.lastAccessTime());
                // System.out.println("  lastModifiedTime: " + attr.lastModifiedTime());
                // System.out.println("  isDirectory: " + attr.isDirectory());
                // System.out.println("  isOther: " + attr.isOther());
                // System.out.println("  isRegularFile: " + attr.isRegularFile());
                // System.out.println("  isSymbolicLink: " + attr.isSymbolicLink());
                // System.out.println("  size: " + attr.size()); 
                // System.out.println(" ");

                //creating intermediate JSON
                JSONObject intermediate = new JSONObject();
                intermediate.put("filename", basePath);
                intermediate.put("timestamp", String.valueOf((new Date()).getTime()));
                intermediate.put("namespace", getMacAddress());

                intermediate.put("creationTime", String.valueOf(attr.creationTime()));
                intermediate.put("lastAccessTime", String.valueOf(attr.lastAccessTime()));
                intermediate.put("lastModifiedTime", String.valueOf(attr.lastModifiedTime()));
                intermediate.put("isDirectory", String.valueOf(attr.isDirectory()));
                intermediate.put("isOther", String.valueOf(attr.isOther()));
                intermediate.put("isRegularFile", String.valueOf(attr.isRegularFile()));
                intermediate.put("isSymbolicLink", String.valueOf(attr.isSymbolicLink()));
                intermediate.put("size", attr.size());

                // Create intermediate temp file
                nameCount += 1;
                String intermediateName = "/generated" + String.valueOf(nameCount) + ".json";
                String finalName = tempFileDirAbsolute + intermediateName;
                FileWriter generated = new FileWriter(finalName);
                generated.write(intermediate.toJSONString());
                generated.flush();
                generated.close();

                // Create one work unit for each file to pull
                WorkUnit workUnit = new WorkUnit(state, extract);
                workUnit.setProp(SOURCE_FILE_KEY, finalName);
                workUnits.add(workUnit);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // write out number of files found to temp file
        try {
            FileWriter numCsvFiles = new FileWriter(tempFileDirAbsolute + "/numCsvFiles.txt");
            numCsvFiles.write("" + csvCount);
            numCsvFiles.flush();
            numCsvFiles.close();

            FileWriter numFiles = new FileWriter(tempFileDirAbsolute + "/numFiles.txt");
            numFiles.write("" + nameCount);
            numFiles.flush();
            numFiles.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    return workUnits;
}

From source file:com.gendai.modcreatorfx.template.ItemTemplate.java

/**
 * Set up all the directory used then for generating the java files.
 * Also get the texture file and the json({@link JSONObject}) file and modify as needed.
 *//*from   www . j a  v  a  2s  .com*/
@SuppressWarnings("unchecked")
private void config() {
    javaDir = new File(Reference.OUTPUT_LOCATION + mod.getName() + "/java/" + mod.getName());
    javaDir.mkdirs();
    resDir = new File(
            Reference.OUTPUT_LOCATION + mod.getName() + "/resources/assets/" + mod.getName().toLowerCase());
    resDir.mkdirs();
    proxyDir = new File(javaDir + "/proxy");
    proxyDir.mkdirs();
    initDir = new File(javaDir + "/init");
    initDir.mkdirs();
    itemsDir = new File(javaDir + "/items");
    itemsDir.mkdirs();
    langDir = new File(resDir.getPath() + "/lang/en_US.lang");
    langDir.getParentFile().mkdirs();
    modelDir = new File(resDir.getPath() + "/models/item/" + item.getName().toLowerCase() + ".json");
    modelDir.getParentFile().mkdirs();
    try {
        langDir.createNewFile();
        FileWriter fw = new FileWriter(langDir.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write("item." + item.getName() + ".name=" + item.getName());
        bw.close();
        //modeldir.createNewFile();
        Files.copy(
                Paths.get(Resource.class.getResource(item.getType().name() + ".json").getPath().substring(3)),
                Paths.get(modelDir.toString()));
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(new FileReader(modelDir.toString()));
        JSONObject jsonObject = (JSONObject) obj;
        JSONObject arr = (JSONObject) jsonObject.get("textures");
        arr.put("layer0", mod.getName().toLowerCase() + ":items/" + item.getName().toLowerCase());
        FileWriter file = new FileWriter(modelDir.toString());
        String rep = jsonObject.toString().replace("\\/", "/");
        file.write(rep);
        file.flush();
        file.close();
    } catch (IOException | ParseException e1) {
        e1.printStackTrace();
    }
    res = item.getTexturefile();
    Path pathto = Paths.get(resDir.getPath() + "/textures/items/" + item.getName().toLowerCase() + ".png");
    pathto.toFile().getParentFile().mkdirs();
    try {
        Files.copy(res.toPath(), pathto);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:wsattacker.plugin.dos.dosExtension.result.ResultGenerator.java

private void saveResponseTimeOfTestRequests(File testRequests) throws IOException {
    // Save responseTime of TestProbes!
    FileWriter writer = new FileWriter(testRequests);

    saveResponseTime(writer, attackModel.getLogListTestProbeRequests());

    writer.flush();
    writer.close();//from  w  w  w.j  a v  a  2 s . co  m
}

From source file:wsattacker.plugin.dos.dosExtension.result.ResultGenerator.java

private void saveResponseTimeOfTamperedRequests(File tamperedRequests) throws IOException {
    // Save responseTime of tampered requests!
    FileWriter writer = new FileWriter(tamperedRequests);

    saveResponseTime(writer, attackModel.getLogListTamperedRequests());

    writer.flush();
    writer.close();/*from  w w w. j ava 2s  .  c  o m*/
}

From source file:com.ewcms.publication.PublishIntegratedTest.java

public void runPublishSite() throws Exception {
    //        updateTemplateSourceStutas();
    //        updateResourceStutas();
    //        updateArticleStutas();

    PublishServiceable publishService = getPublishService();
    publishService.publishSite(-2, true, "admin");

    int seq = 0;// w  w  w  .  j a va  2 s . co m
    File file = new File("/tmp/progress/");
    FileUtils.deleteQuietly(file);
    file.mkdir();
    while (true) {
        FileWriter writer = new FileWriter("/tmp/progress/" + String.valueOf(seq) + ".txt");
        List<Taskable> tasks = publishService.getSitePublishTasks(-2);
        if (tasks.isEmpty()) {
            publishService.closeSitePublish(-2);
        }
        for (Taskable task : tasks) {
            writerDepender(writer, task, 0);
        }
        writer.flush();
        writer.close();
        seq++;
        Thread.sleep(1000 * 60);
    }
}

From source file:com.intuit.tank.http.xml.GenericXMLHandler.java

/**
 * Save the xml to a file// w w w.j a  v a 2s  .  c o m
 */
public void Save() {
    try {
        XMLOutputter out = new XMLOutputter();
        java.io.FileWriter writer = new java.io.FileWriter(this.xmlFile);
        out.output(this.xmlDocument, writer);
        writer.flush();
        writer.close();
    } catch (Exception ex) {
        LOG.error("Error in handler: " + ex.getMessage(), ex);
    }
}

From source file:jt56.comm.code.util.CreateBean.java

public void createFile(String path, String fileName, String str) throws IOException {
    FileWriter writer = new FileWriter(new File(path + fileName));
    writer.write(new String(str.getBytes("utf-8")));
    writer.flush();
    writer.close();/*w w w.j a  va2s . com*/
}