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.mycompany.myelasticsearch.DocumentReader.java

public static void getAllCapitalWords(String docText) {
    Set<String> allCapsWords = new HashSet<>();
    Pattern p = Pattern.compile("\\b[A-Z]{2,}\\b");
    Matcher m = p.matcher(docText);
    while (m.find()) {
        String word = m.group();/* w ww  .  j  a  va2  s.  c om*/
        // System.out.println(word);
        allCapsWords.add(word);
    }

    for (String allcaps : allCapsWords) {
        System.out.println(allcaps);
    }
    System.out.println("Caps word count" + allCapsWords.size());
    org.json.simple.JSONObject obj = new org.json.simple.JSONObject();
    int count = 0;
    for (String output : outputArray) {
        obj.put(String.valueOf(count), output.replaceAll("\\s+", " "));
        count++;
    }
    try {

        FileWriter file = new FileWriter("CapsWord.txt");
        file.write(obj.toJSONString());
        file.flush();
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:de.tor.tribes.util.AttackToTextWriter.java

private static boolean writeBlocksToFiles(List<String> pBlocks, Tribe pTribe, File pPath) {
    int fileNo = 1;
    String baseFilename = pTribe.getName().replaceAll("\\W+", "");
    for (String block : pBlocks) {
        String fileName = FilenameUtils.concat(pPath.getPath(), baseFilename + fileNo + ".txt");
        FileWriter w = null;
        try {/*from   w  w w .j a v a2 s . c  o  m*/
            w = new FileWriter(fileName);
            w.write(block);
            w.flush();
            w.close();
        } catch (IOException ioe) {
            logger.error("Failed to write attack to textfile", ioe);
            return false;
        } finally {
            if (w != null) {
                try {
                    w.close();
                } catch (IOException ignored) {
                }
            }
        }
        fileNo++;
    }
    return true;
}

From source file:com.yahoo.storm.yarn.StormMasterCommand.java

public static void downloadStormYaml(StormMaster.Client client, String storm_yaml_output) {
    String conf_str = "Not Avaialble";

    //fetch storm.yaml from Master
    try {/*from w  w  w  .j a  v  a  2s  .c  o m*/
        conf_str = client.getStormConf();
    } catch (TTransportException ex) {
        LOG.error("Exception in downloading storm.yaml", ex);
    } catch (TException ex) {
        LOG.error("Exception in downloading storm.yaml", ex);
    }

    //storm the fetched storm.yaml into storm_yaml_output or stdout
    try {
        Object json = JSONValue.parse(conf_str);
        Map<?, ?> conf = (Map<?, ?>) json;
        Yaml yaml = new Yaml();

        if (storm_yaml_output == null) {
            LOG.info("storm.yaml downloaded:");
            System.out.println(yaml.dump(conf));
        } else {
            FileWriter out = new FileWriter(storm_yaml_output);
            yaml.dump(conf, out);
            out.flush();
            out.close();
            LOG.info("storm.yaml downloaded into " + storm_yaml_output);
        }
    } catch (Exception ex) {
        LOG.error("Exception in storing storm.yaml. ", ex);
    }
}

From source file:io.github.casnix.spawnerdropper.SpawnerStack.java

public static boolean PutSpawnerIntoService(String spawnerType) {
    // Read ./SpawnerDropper.SpawnerStack.json into a string

    // get the value of JSON->{spawnerType} and add 1 to it.

    // Write file back to disk
    try {/*from w  ww . j a  va2 s  .co  m*/
        // Read entire ./SpawnerDropper.SpawnerStack.json into a string
        String spawnerStack = new String(
                Files.readAllBytes(Paths.get("./plugins/SpawnerDropper/SpawnerStack.json")));

        // get the value of JSON->{spawnerType}
        JSONParser parser = new JSONParser();

        Object obj = parser.parse(spawnerStack);

        JSONObject jsonObj = (JSONObject) obj;

        long numberInService = (Long) jsonObj.get(spawnerType);

        if (numberInService < 0) {
            numberInService = 0;
        }

        //         System.out.println("[SD DBG MSG] PSIS numberInServer("+numberInService+")");
        numberInService += 1;
        jsonObj.put(spawnerType, new Long(numberInService));

        FileWriter file = new FileWriter("./plugins/SpawnerDropper/SpawnerStack.json");
        file.write(jsonObj.toJSONString());
        file.flush();
        file.close();

        return true;
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[SpawnerDropper] Caught ParseException in PutSpawnerIntoService(String)");
        e.printStackTrace();

        return false;
    } catch (FileNotFoundException e) {
        Bukkit.getLogger()
                .warning("[SpawnerDropper] Could not find ./plugins/SpawnerDropper/SpawnerStack.json");
        e.printStackTrace();

        return false;
    } catch (IOException e) {
        Bukkit.getLogger().warning("[SpawnerDropper] Caught IOException in PutSpawnerIntoService(String)");
        e.printStackTrace();

        return false;
    }
}

From source file:fridgegameinstaller.MCJsonConf.java

public static void getJson(String path, int mb) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet("http://api.fridgegame.com/mcconf/Fridgegame.json");

    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    try {//from   w w  w  .  j  av  a 2  s  . c  o m
        System.out.println(httpGet.toString());
        System.out.println(response1.getStatusLine());
        BufferedReader br = new BufferedReader(new InputStreamReader(response1.getEntity().getContent()));
        String a;
        String output = "";
        while ((a = br.readLine()) != null) {
            output += a + "\n";
        }
        System.out.println(output);
        try {

            JSONObject json = new JSONObject(output);
            String mcArgs = json.getString("minecraftArguments");
            String regex = "(-Xmx[^ ]*)";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(mcArgs);
            String newArgs = m.replaceAll("-Xmx" + mb + "M");
            json.put("minecraftArguments", newArgs);
            FileWriter file = new FileWriter(path);

            try {
                file.write(json.toString());

            } catch (IOException e) {
                e.printStackTrace();

            } finally {
                file.flush();
                file.close();
            }

        } catch (JSONException e) {

        }
    } finally {
        response1.close();
    }

}

From source file:io.github.casnix.spawnerdropper.SpawnerStack.java

public static boolean TakeSpawnerOutOfService(String spawnerType) {
    // Read ./SpawnerDropper.SpawnerStack.json into a string

    // get the value of JSON->{spawnerType} and subtract 1 to it unless it is 0.
    // If it's zero, return false

    // Write file back to disk
    try {//  w ww. j  av a  2  s.  co m
        // Read entire ./SpawnerDropper.SpawnerStack.json into a string
        String spawnerStack = new String(
                Files.readAllBytes(Paths.get("./plugins/SpawnerDropper/SpawnerStack.json")));

        // get the value of JSON->{spawnerType}
        JSONParser parser = new JSONParser();

        Object obj = parser.parse(spawnerStack);

        JSONObject jsonObj = (JSONObject) obj;

        long numberInService = (Long) jsonObj.get(spawnerType);

        if (numberInService <= 0) {
            return false;
        } else {
            //            System.out.println("[SD DBG MSG] TSOOS numberInServer("+numberInService+")");

            numberInService -= 1;
            jsonObj.put(spawnerType, new Long(numberInService));

            FileWriter file = new FileWriter("./plugins/SpawnerDropper/SpawnerStack.json");
            file.write(jsonObj.toJSONString());
            file.flush();
            file.close();

            return true;
        }
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[SpawnerDropper] Caught ParseException in TakeSpawnerOutOfService(String)");
        e.printStackTrace();

        return false;
    } catch (FileNotFoundException e) {
        Bukkit.getLogger()
                .warning("[SpawnerDropper] Could not find ./plugins/SpawnerDropper/SpawnerStack.json");
        e.printStackTrace();

        return false;
    } catch (IOException e) {
        Bukkit.getLogger().warning("[SpawnerDropper] Caught IOException in TakeSpawnerOutOfService(String)");
        e.printStackTrace();

        return false;
    }
}

From source file:bizlogic.Sensors.java

public static void list(Connection DBcon) throws IOException, ParseException, SQLException {

    Statement st = null;//  w ww  . j av a2 s.com
    ResultSet rs = null;

    try {
        st = DBcon.createStatement();
        rs = st.executeQuery("SELECT * FROM USERCONF.SENSORLIST");

    } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Sensors.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);
    }
    try {
        FileWriter sensorsFile = new FileWriter("/var/lib/tomcat8/webapps/ROOT/Records/sensors.json");
        sensorsFile.write("");
        sensorsFile.flush();

        JSONParser parser = new JSONParser();

        JSONObject Records = new JSONObject();

        JSONObject operation_Obj = new JSONObject();
        JSONObject operand_Obj = new JSONObject();
        JSONObject unit_Obj = new JSONObject();
        JSONObject name_Obj = new JSONObject();
        JSONObject ip_Obj = new JSONObject();
        JSONObject port_Obj = new JSONObject();

        int _total = 0;

        JSONArray sensorList = new JSONArray();

        while (rs.next()) {

            JSONObject sensor_Obj = new JSONObject();
            int id = rs.getInt("sensor_id");
            String operation = rs.getString("operation");
            int operand = rs.getInt("operand");
            String unit = rs.getString("unit");
            String name = rs.getString("name");
            String ip = rs.getString("IP");
            int port = rs.getInt("port");

            sensor_Obj.put("recid", id);
            sensor_Obj.put("operation", operation);
            sensor_Obj.put("operand", operand);
            sensor_Obj.put("unit", unit);
            sensor_Obj.put("name", name);
            sensor_Obj.put("IP", ip);
            sensor_Obj.put("port", port);

            sensorList.add(sensor_Obj);
            _total++;

        }
        rs.close();

        Records.put("total", _total);
        Records.put("records", sensorList);

        sensorsFile.write(Records.toJSONString());
        sensorsFile.flush();
        sensorsFile.close();
    }

    catch (IOException ex) {
        Logger.getLogger(Sensors.class.getName()).log(Level.WARNING, null, ex);
    }
}

From source file:com.bluexml.side.m2.repositoryBuilder.Builder.java

private static void writeDotFile(File rootPlugins, String output) throws Exception, IOException {
    SideOptionsTree sot = new SideOptionsTree();
    sot.extensionPointRenderer(rootPlugins);

    File outputFile = new File(output);
    FileWriter fw = new FileWriter(outputFile);
    DotRenderer dotRenderer = new DotRenderer(fw, sot.getParentChildren(), sot.getNode2NodeType());
    dotRenderer.render();//from   w ww .ja v  a2  s .  c om
    fw.flush();
    fw.close();
}

From source file:co.foxdev.foxbot.utils.Utils.java

public static boolean addCustomCommand(String channel, String command, String text) {
    String filePath = "data/custcmds/" + channel.substring(1);
    File path = new File(filePath);

    try {/*from  www.  ja va  2  s  . c  o m*/
        if (!path.exists() && !path.mkdirs()) {
            foxbot.getLogger().warn("Error occurred while creating custom command folders!");
        }

        File file = new File(filePath + "/" + command);

        if (file.exists() && !file.delete()) {
            foxbot.getLogger().warn(
                    String.format("Error occurred while deleting command '%s' for %s!", command, channel));
        }

        if (text.isEmpty() || text.equalsIgnoreCase("delete")) {
            if (file.delete()) {
                foxbot.getLogger().warn(String.format("Command '%s' deleted for %s!", command, channel));
            }
            return false;
        }

        FileWriter fw = new FileWriter(filePath + "/" + command);
        BufferedWriter bw = new BufferedWriter(fw);

        bw.write(text);
        bw.flush();
        bw.close();
        fw.flush();
        fw.close();
        foxbot.getLogger()
                .warn(String.format("Command '%s' set for %s at %s", command, channel, file.getAbsolutePath()));
    } catch (IOException ex) {
        foxbot.getLogger().error("Error occurred while adding custom command", ex);
    }
    return true;
}

From source file:net.portalblock.untamedchat.bungee.UCConfig.java

public static void load() {
    final String NEW_LINE = System.getProperty("line.separator");
    File cfgDir = new File("plugins/UntamedChat");
    if (!cfgDir.exists()) {
        UntamedChat.getInstance().getLogger().info("No config directory found, generating one now!");
        cfgDir.mkdir();/*from w ww. j av  a2 s .c  o  m*/
    }
    File configFile = new File(cfgDir + "/config.json");
    if (!configFile.exists()) {
        UntamedChat.getInstance().getLogger().info("No config file found, generating one now!");
        try {
            configFile.createNewFile();
            InputStream is = UCConfig.class.getResourceAsStream("/config.json");
            String line;
            if (is == null)
                throw new NullPointerException("is");
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            FileWriter configWriter = new FileWriter(configFile);
            while ((line = reader.readLine()) != null) {
                configWriter.write(line + NEW_LINE);
            }
            configWriter.flush();
            configWriter.close();
            reader.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        BufferedReader reader = new BufferedReader(new FileReader(configFile));
        StringBuilder configBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            configBuilder.append(line);
        }
        JSONObject config = new JSONObject(configBuilder.toString());
        TARGET_FORMAT = config.optString("target_format", "&6{sender} &7-> &6Me&7: {msg}");
        SENDER_FORMAT = config.optString("sender_format", "&6Me &7-> &6{target}&7: {msg}");
        SOCIAL_SPY_FORMAT = config.optString("social_spy_format", "{sender} -> {target}: {msg}");
        GLOBAL_FORMAT = config.optString("global_format", "&7[&6{server}&7] [&6{sender}&7]: &r{msg}");
        gcDefault = config.optBoolean("global_chat_default", false);
        chatCoolDowns = config.optBoolean("enable_chat_cooldown", true);
        spDefault = config.optBoolean("social_spy_default", false);
        chatCooldown = config.optLong("chat_cooldown", 10);
        SPAM_MESSAGE = config.optString("spam_message", "&7[&cUntamedChat&7] &cDon't spam the chat!");
        JSONObject commands = config.optJSONObject("commands");
        if (commands == null) {
            msgAliases = new String[] { "msg", "m" };
            replyAliases = new String[] { "reply", "r" };
            globalAliases = new String[] { "globalchat", "global", "g" };
            socialSpyAliases = new String[] { "socialspy", "sp", "spy" };
        } else {
            msgAliases = makeCommandArray(commands.optJSONArray("msg"), "msg", "m");
            replyAliases = makeCommandArray(commands.optJSONArray("reply"), "reply", "r");
            globalAliases = makeCommandArray(commands.optJSONArray("global_chat"), "globalchat", "global", "g");
            socialSpyAliases = makeCommandArray(commands.optJSONArray("social_spy"), "socialspy", "sp", "spy");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}