Example usage for java.io FileWriter FileWriter

List of usage examples for java.io FileWriter FileWriter

Introduction

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

Prototype

public FileWriter(FileDescriptor fd) 

Source Link

Document

Constructs a FileWriter given a file descriptor, using the platform's java.nio.charset.Charset#defaultCharset() default charset .

Usage

From source file:dataGen.DataGen.java

/**
 * Creates normal or uniform distributed Test-Data, without correlation.
 * The resulting Data is stored in the resources Folder.
 * @param dimensions//from ww  w .  j  a  v a2 s  .c  om
 *       The dimension count of the resulting Data
 * @param rowCount
 *       How many data tuples should be created?
 * @throws IOException
 *       If Stream to a File couldn't be written/closed 
 */
public static void genData(int dimensions, int rowCount) throws IOException {
    logger.info("Generating uniform random Data with " + rowCount + " Tuples in " + dimensions + " dimensions");
    Writer fw = new FileWriter("src/main/resources/random-" + rowCount + "-" + dimensions + ".dat");
    Random gen = new Random();

    for (int i = 1; i <= rowCount; i++) {
        // Each Row should start with the Row count
        String row = i + " ";
        // Files should be created OS/Language independent
        DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance();
        dfs.setDecimalSeparator('.');
        NumberFormat nf = new DecimalFormat("0.000000000", dfs);

        for (int j = 0; j < dimensions; j++) {
            Float n = gen.nextFloat();
            row = row + nf.format(n) + " ";
        }
        fw.write(row);
        fw.append(System.getProperty("line.separator"));
    }
    fw.close();
    logger.info(rowCount + " entries generated");
}

From source file:edu.cornell.mannlib.vitro.webapp.ontology.update.SimpleChangeRecord.java

public SimpleChangeRecord(String additionsFile, String retractionsFile) {
    this.additionsFile = new File(additionsFile);
    try {//  w w w . j  a  v a 2  s . com
        FileWriter test = new FileWriter(additionsFile);
    } catch (IOException ioe) {
        throw new RuntimeException(
                this.getClass().getName() + " unable to create required file at " + additionsFile);
    }
    this.retractionsFile = new File(retractionsFile);
    try {
        FileWriter test = new FileWriter(retractionsFile);
    } catch (IOException ioe) {
        throw new RuntimeException(
                this.getClass().getName() + " unable to create required file at " + retractionsFile);
    }
}

From source file:manager.GameElement.java

public static void save() throws IOException {
    BufferedWriter bw = new BufferedWriter(new FileWriter("scores.json"));
    bw.write(toJSON().toJSONString());/*  www. j  ava 2 s. c o  m*/
    bw.flush();
}

From source file:com.cws.esolutions.security.main.PasswordUtility.java

public static void main(final String[] args) {
    final String methodName = PasswordUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {/* www  .ja va2s .c  o m*/
        DEBUGGER.debug("Value: {}", methodName);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(PasswordUtility.CNAME, options, true);

        System.exit(1);
    }

    BufferedReader bReader = null;
    BufferedWriter bWriter = null;

    try {
        // load service config first !!
        SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG,
                false);

        if (DEBUG) {
            DEBUGGER.debug("Options options: {}", options);

            for (String arg : args) {
                DEBUGGER.debug("Value: {}", arg);
            }
        }

        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
            DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions());
            DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList());
        }

        final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData();
        final SecurityConfig secConfig = secConfigData.getSecurityConfig();
        final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo();
        final SystemConfig systemConfig = secConfigData.getSystemConfig();

        if (DEBUG) {
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
            DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig);
            DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig);
            DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig);
        }

        if (commandLine.hasOption("encrypt")) {
            if ((StringUtils.isBlank(repoConfig.getPasswordFile()))
                    || (StringUtils.isBlank(repoConfig.getSaltFile()))) {
                System.err.println("The password/salt files are not configured. Entries will not be stored!");
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            final String entryName = commandLine.getOptionValue("entry");
            final String username = commandLine.getOptionValue("username");
            final String password = commandLine.getOptionValue("password");
            final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
                DEBUGGER.debug("String password: {}", password);
                DEBUGGER.debug("String salt: {}", salt);
            }

            final String encodedSalt = PasswordUtils.base64Encode(salt);
            final String encodedUserName = PasswordUtils.base64Encode(username);
            final String encryptedPassword = PasswordUtils.encryptText(password, salt,
                    secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                    secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                    systemConfig.getEncoding());
            final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword);

            if (DEBUG) {
                DEBUGGER.debug("String encodedSalt: {}", encodedSalt);
                DEBUGGER.debug("String encodedUserName: {}", encodedUserName);
                DEBUGGER.debug("String encodedPassword: {}", encodedPassword);
            }

            if (commandLine.hasOption("store")) {
                try {
                    new File(passwordFile.getParent()).mkdirs();
                    new File(saltFile.getParent()).mkdirs();

                    boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile();

                    if (DEBUG) {
                        DEBUGGER.debug("saltFileExists: {}", saltFileExists);
                    }

                    // write the salt out first
                    if (!(saltFileExists)) {
                        throw new IOException("Unable to create salt file");
                    }

                    boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile();

                    if (!(passwordFileExists)) {
                        throw new IOException("Unable to create password file");
                    }

                    if (commandLine.hasOption("replace")) {
                        File[] files = new File[] { saltFile, passwordFile };

                        if (DEBUG) {
                            DEBUGGER.debug("File[] files: {}", (Object) files);
                        }

                        for (File file : files) {
                            if (DEBUG) {
                                DEBUGGER.debug("File: {}", file);
                            }

                            String currentLine = null;
                            File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile");

                            if (DEBUG) {
                                DEBUGGER.debug("File tmpFile: {}", tmpFile);
                            }

                            bReader = new BufferedReader(new FileReader(file));
                            bWriter = new BufferedWriter(new FileWriter(tmpFile));

                            while ((currentLine = bReader.readLine()) != null) {
                                if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) {
                                    bWriter.write(currentLine + System.getProperty("line.separator"));
                                    bWriter.flush();
                                }
                            }

                            bWriter.close();

                            FileUtils.deleteQuietly(file);
                            FileUtils.copyFile(tmpFile, file);
                            FileUtils.deleteQuietly(tmpFile);
                        }
                    }

                    FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt
                            + System.getProperty("line.separator"), true);
                    FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + ","
                            + encodedPassword + System.getProperty("line.separator"), true);
                } catch (IOException iox) {
                    ERROR_RECORDER.error(iox.getMessage(), iox);
                }
            }

            System.out.println("Entry Name " + entryName + " stored.");
        }

        if (commandLine.hasOption("decrypt")) {
            String saltEntryName = null;
            String saltEntryValue = null;
            String decryptedPassword = null;
            String passwordEntryName = null;

            if ((StringUtils.isEmpty(commandLine.getOptionValue("entry"))
                    && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) {
                throw new ParseException("No entry or username was provided to decrypt.");
            }

            if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) {
                throw new ParseException("no entry provided to decrypt");
            }

            String entryName = commandLine.getOptionValue("entry");
            String username = commandLine.getOptionValue("username");

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) {
                throw new IOException(
                        "Unable to read configured password/salt file. Please check configuration and/or permissions.");
            }

            for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) {
                saltEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String saltEntryName: {}", saltEntryName);
                }

                if (StringUtils.equals(saltEntryName, entryName)) {
                    saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    break;
                }
            }

            if (StringUtils.isEmpty(saltEntryValue)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) {
                passwordEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName);
                }

                if (StringUtils.equals(passwordEntryName, saltEntryName)) {
                    String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue,
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            systemConfig.getEncoding());

                    break;
                }
            }

            if (StringUtils.isEmpty(decryptedPassword)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            System.out.println(decryptedPassword);
        } else if (commandLine.hasOption("encode")) {
            System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0)));
        } else if (commandLine.hasOption("decode")) {
            System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0)));
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        System.err.println("An error occurred during processing: " + iox.getMessage());
        System.exit(1);
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
        System.exit(1);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
        System.exit(1);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
        System.exit(1);
    } finally {
        try {
            if (bReader != null) {
                bReader.close();
            }

            if (bWriter != null) {
                bReader.close();
            }
        } catch (IOException iox) {
        }
    }

    System.exit(0);
}

From source file:net.sourceforge.jcctray.utils.ObjectPersister.java

public static void saveSettings(IJCCTraySettings settings, String fileName) throws IOException {
    FileWriter outputWriter = new FileWriter(fileName);
    saveSettings(settings, outputWriter);
}

From source file:com.evidon.areweprivateyet.Crawler.java

private void recordLog(String name) throws IOException {
    BufferedWriter out = new BufferedWriter(new FileWriter(path + "crawl-" + name + ".log"));
    out.write(out.toString());/*  w w  w .ja  va  2 s  .  com*/
    out.close();
}

From source file:ir.pooyahfp.matrixcli.ProgramTest.java

@Test
public void testLoadCommandFile() throws Exception {
    String path = "test.txt";
    BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path)));
    writer.write("matrix x 3 3");
    writer.newLine();//  w  w w .j a  v  a  2 s .  co m
    writer.write("show x");
    writer.flush();
    writer.close();

    program.loadCommandFile(path);
}

From source file:me.ardacraft.blocksapi.helper.LangHelper.java

public static void writeLangFile() {
    File out = FileHelper.externalConfigFile("assets/acblocks/lang", "en_US.lang");
    try {// w w w . j av  a2 s  .  c  o  m
        FileWriter writer = new FileWriter(out);
        Collections.sort(entries);
        for (String s : entries) {
            writer.write(s);
            writer.append("\n");
        }
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    entries.clear();
}

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();//  w w  w  . j av a2 s  .co 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();
    }
}

From source file:JSON.WriteProductJSON.java

public int write() {
    products.put("products", details);
    try {/* www.  j ava  2s  .c o  m*/

        // Writing to a file  
        File file = new File("Path to products.json");
        file.createNewFile();
        FileWriter fileWriter = new FileWriter(file);
        System.out.println("Writing JSON object to file");
        System.out.println("-----------------------");
        System.out.print(products);

        fileWriter.write(products.toJSONString());
        fileWriter.flush();
        fileWriter.close();

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