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:bizlogic.Sensors.java

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

    Statement st = null;//from   ww  w  .j a v a 2s . c o  m
    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:net.sourceforge.jcctray.utils.ObjectPersister.java

private static void saveCruiseImpls(FileWriter writer, Collection cruiseImpls) throws IOException {
    for (Iterator iterator = cruiseImpls.iterator(); iterator.hasNext();) {
        writer.write("      <cruiseImpl>" + ((Class) iterator.next()).getName() + "</cruiseImpl>\n");
    }//from   www .j  a v a2 s .c  om
}

From source file:no.uib.tools.OnthologyHttpClient.java

public static List<String> getTermDescendants(String onthologyName, String term, String relation) {
    List<String> result = new ArrayList<>();
    String queryContent = "";

    onthologySize = getOntologySize(onthologyName);
    String uri = createUri(onthologyName, term, relation);
    //BufferedReader br = getContentBufferedReader(uri);
    //String queryContent = convertBufferedReader(br);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(uri);
    getRequest.addHeader("accept", "application/json");

    HttpResponse response;//from   ww w  . j  a v  a  2s  .  c  o  m
    try {
        response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed to get the PSIMOD onthology : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String line;
        FileWriter fw = new FileWriter("./mod.json");

        while ((line = br.readLine()) != null) {
            fw.write(line);
            queryContent += line;
        }

        fw.close();
        httpClient.getConnectionManager().shutdown();

        char c;
        int matched = 0;
        String mod = "";
        int pos = 0;

        while (pos < queryContent.length()) {
            c = queryContent.charAt(pos);
            pos++;
            if (c == pattern.charAt(matched)) {
                matched++;
                if (matched == pattern.length()) {
                    for (int I = 0; I < 5; I++) {
                        mod += queryContent.charAt(pos);
                        pos++;
                    }
                    result.add(mod);
                    mod = "";
                    matched = 0;
                }
            } else {
                matched = 0;
            }
        }

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

    return result;
}

From source file:com.thruzero.common.core.utils.FileUtilsExt.java

/**
 * Append the given {@code data} to the specified {@code file}.
 *///  ww  w  . j a va 2  s. c  o m
public static void appendToFile(final File file, final String data) throws IOException {
    FileWriter fw = new FileWriter(file, true);
    fw.write(data);
    fw.close();
}

From source file:Main.java

public static Boolean canWrite(File f) {
    if (f.isDirectory()) {
        FileWriter w = null;
        String testFilename = f.getPath() + "/.EASYRPG_WRITE_TEST";
        try {/* ww  w .j av a  2 s .c om*/
            w = new FileWriter(testFilename);
            // Permissions are checked on open, but it is Android, better be save
            w.write("Android >.<");
        } catch (IOException e) {
            return false;
        } finally {
            try {
                if (w != null) {
                    w.close();
                }
            } catch (IOException e) {
            }
        }

        File testFile = new File(testFilename);
        if (testFile.exists()) {
            // Does not throw
            testFile.delete();
        }
    } else {
        boolean deleteAfter = f.exists();
        try {
            FileWriter w = new FileWriter(f, true);
            w.close();
        } catch (IOException e) {
            return false;
        }

        if (deleteAfter) {
            f.delete();
        }
    }

    return true;
}

From source file:de.tudarmstadt.ukp.lmf.transform.sensealignments.FrameNetWiktionaryAlignment.java

/**
 * //w  w  w  .j  a v  a  2 s . c om
 * @param classifierOut - output tsv of weka classification
 * @param classifierIn - data section of arff input file for classification
 *        (contains ids in same order as classifications in classifierOut)
 * @param tsvFile
 * @throws IOException 
 */
public static void classifierOutputToTsv(String classifierOut, String classifierIn, String tsvFile)
        throws IOException {
    List<String> res = new ArrayList<String>();
    // read classification
    InputStream is = new BufferedInputStream(new FileInputStream(new File(classifierOut)));
    Reader reader = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(reader);
    String line = br.readLine();
    line = br.readLine();
    ArrayList<String> scoreLines = new ArrayList<String>();
    while (line != null) {
        scoreLines.add(line);
        line = br.readLine();
        System.out.println(scoreLines.size());
    }
    // read ids
    InputStream is2 = new BufferedInputStream(new FileInputStream(new File(classifierIn)));
    Reader reader2 = new InputStreamReader(is2);
    BufferedReader br2 = new BufferedReader(reader2);
    String line2 = br2.readLine();
    line2 = br2.readLine();
    ArrayList<String> idLines = new ArrayList<String>();
    while (line2 != null) {
        idLines.add(line2);
        line2 = br2.readLine();
    }
    System.out.println(scoreLines.size());
    System.out.println(idLines.size());
    if (scoreLines.size() != idLines.size()) {// 
        logger.warn("files do not agree");
    }
    int positive = 0;
    int negative = 0;
    for (int i = 0; i < scoreLines.size(); i++) {
        String[] scoreitems = scoreLines.get(i).split(":");
        String[] iditems = idLines.get(i).split(",");
        String first = iditems[0];
        String second = iditems[1];
        String sysScore = scoreitems[2].split(",")[0];
        if (sysScore.equals("1")) {// pair classified as alignment
            res.add(first + "\t" + second);
            positive++;
        } else {
            negative++;
        }
    }
    logger.info("positive class-->added as alignment: " + positive);
    logger.info("negative class-->no alignment: " + negative);
    System.out.println("write positive class to file");
    FileWriter fw = new FileWriter(new File(tsvFile));
    for (String r : res) {
        fw.write(r + "\n");
    }
    fw.close();
    br2.close();
    br.close();
}

From source file:hd3gtv.mydmam.auth.AuthenticationBackend.java

public static void checkFirstPlayBoot() throws Exception {
    if (authenticators == null) {
        throw new NullPointerException("No backend");
    }/*ww w.j a v  a2 s  .  c  o  m*/
    if (authenticators.size() == 0) {
        throw new NullPointerException("No backend");
    }
    if ((authenticators.get(0) instanceof AuthenticatorLocalsqlite) == false) {
        /**
         * Admin has set a configuration : no need to setup a first boot
         */
        return;
    }
    AuthenticatorLocalsqlite authenticatorlocalsqlite = (AuthenticatorLocalsqlite) authenticators.get(0);
    if (authenticatorlocalsqlite.isUserExists(ACLUser.ADMIN_NAME) == false) {
        String newpassword = passwordGenerator();
        authenticatorlocalsqlite.createUser(ACLUser.ADMIN_NAME, newpassword, "Local Admin", true);

        File textfile = new File("play-new-password.txt");
        FileWriter fw = new FileWriter(textfile, false);
        fw.write("Admin login: " + ACLUser.ADMIN_NAME + "\r\n");
        fw.write("Admin password: " + newpassword + "\r\n");
        fw.write("\r\n");
        fw.write("You should remove this file after keeping this password..\r\n");
        fw.write("\r\n");
        fw.write("You can change this password with mydmam-cli:\r\n");
        fw.write("$ mydmam-cli localauth -f " + authenticatorlocalsqlite.getDbfile().getAbsolutePath()
                + " -key " + authenticatorlocalsqlite.getMaster_password_key() + " -passwd -u "
                + ACLUser.ADMIN_NAME + "\r\n");
        fw.write("\r\n");
        fw.write(
                "Note: you haven't need a local authenticator if you set another backend and if you grant some new administrators\r\n");
        fw.close();

        Log2Dump dump = new Log2Dump();
        dump.add("login", ACLUser.ADMIN_NAME);
        dump.add("password file", textfile.getAbsoluteFile());
        dump.add("local database", authenticatorlocalsqlite.getDbfile());
        Log2.log.security("Create Play administrator account", dump);

    } else if (authenticatorlocalsqlite.isEnabledUser(ACLUser.ADMIN_NAME) == false) {
        throw new Exception("User " + ACLUser.ADMIN_NAME + " is disabled in sqlite file !");
    }

}

From source file:Main.java

public static boolean writeFile(String filePath, String content, boolean append) {
    if (TextUtils.isEmpty(content)) {
        return false;
    }//from   w  w  w .  java2  s  .  c o  m

    FileWriter fileWriter = null;
    try {
        makeDirs(filePath);
        fileWriter = new FileWriter(filePath, append);
        fileWriter.write(content);
        fileWriter.close();
        return true;
    } catch (IOException e) {
        throw new RuntimeException("IOException occurred. ", e);
    } finally {
        if (fileWriter != null) {
            try {
                fileWriter.close();
            } catch (IOException e) {
                throw new RuntimeException("IOException occurred. ", e);
            }
        }
    }
}

From source file:com.cprassoc.solr.auth.util.Utils.java

public static String writeBytesToFile(String filePath, String content) {
    String path = "";
    try {// w ww. ja  v a2s  .c  o m
        File file = new File(filePath);
        FileWriter fw = new FileWriter(file);
        Log.log(Utils.class, "write file: " + filePath);
        fw.write(content);
        //  IOUtils.write(content, fw);
        //  IOUtils.write
        path = file.getAbsolutePath();
        fw.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return path;
}

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 ww w . j  a v  a 2s.  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();
    }
}