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:es.csic.iiia.planes.cli.Cli.java

/**
 * Parse the provided list of arguments according to the program's options.
 * // w ww.j ava2  s. c  o m
 * @param in_args
 *            list of input arguments.
 * @return a configuration object set according to the input options.
 */
private static Configuration parseOptions(String[] in_args) {
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    Properties settings = loadDefaultSettings();

    try {
        line = parser.parse(options, in_args);
    } catch (ParseException ex) {
        Logger.getLogger(Cli.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
        showHelp();
    }

    if (line.hasOption('h')) {
        showHelp();
    }

    if (line.hasOption('d')) {
        dumpSettings();
    }

    if (line.hasOption('s')) {
        String fname = line.getOptionValue('s');
        try {
            settings.load(new FileReader(fname));
        } catch (IOException ex) {
            throw new IllegalArgumentException("Unable to load the settings file \"" + fname + "\"");
        }
    }

    // Apply overrides
    settings.setProperty("gui", String.valueOf(line.hasOption('g')));
    settings.setProperty("quiet", String.valueOf(line.hasOption('q')));
    Properties overrides = line.getOptionProperties("o");
    settings.putAll(overrides);

    String[] args = line.getArgs();
    if (args.length < 1) {
        showHelp();
    }
    settings.setProperty("problem", args[0]);

    Configuration c = new Configuration(settings);
    System.out.println(c.toString());
    /**
     * Modified by Guillermo B. Print settings to a result file, titled
     * "results.txt"
     */
    try {
        FileWriter fw = new FileWriter("results.txt", true);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter out = new PrintWriter(bw);
        String[] results = c.toString().split("\n");
        // out.println(results[8]);

        for (String s : results) {
            out.println(s);

        }
        // out.println(results[2]);
        // out.println(results[8]);
        out.close();
    } catch (IOException e) {
    }

    /**
     * Modified by Ebtesam Save settings to a .csv file, titled
     * "resultsCSV.csv"
     */

    try {
        FileWriter writer = new FileWriter("resultsCSV.csv", true);
        FileReader reader = new FileReader("resultsCSV.csv");

        String header = "SAR Strategy,# of Searcher UAVs,# of Survivors,"
                + "# of Survivors rescued,Min.Time needed to rescue Survivors,Mean. Time needed to rescue Survivors,Max. Time needed to rescue Survivors,"
                + "# of Survivors found,Min. Time needed to find Survivors,Mean Time needed to find Survivors,Max. Time needed to find Survivors,"
                + "Running Time of Simulation\n";
        if (reader.read() == -1) {
            writer.append(header);
            writer.append("\n");
        }
        reader.close();
        String[] results = c.toString().split("\n");
        writer.append(results[2].substring(10));
        writer.append(",");
        writer.append(results[20].substring(11));
        writer.append(",");
        writer.append(results[30].substring(18));
        writer.write(",");
        writer.close();
    } catch (IOException e) {
    }

    if (line.hasOption('t')) {
        System.exit(0);
    }
    return c;
}

From source file:com.bingzer.android.driven.Credential.java

public void save(String name) {
    FileWriter writer = null;
    try {//from www.ja  v a 2 s. co m
        writer = new FileWriter(getCredentialFile(name));
        writer.write(toString());
        writer.flush();
        writer.close();
    } catch (IOException e) {
        Log.e(TAG, "Failed to save credentials to file", e);
    } finally {
        safeClose(writer);
    }
}

From source file:main.java.miro.validator.fetcher.RsyncFetcher.java

public void writePrefetchURIsToFile() {
    try {//from  w w  w  .  ja  v  a  2  s .c  om
        FileWriter writer = new FileWriter(prefetchURIstorage, false);
        for (URI uri : prefetchURIs) {
            writer.write(uri.toString());
            writer.write('\n');
        }
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException();
    }
}

From source file:de.uzk.hki.da.grid.CTIrodsCommandLineConnector.java

private File createTestFile() throws IOException {
    new File(tmpDir).mkdir();
    File temp = new File(tmpDir + "urn.tar");
    FileWriter writer = new FileWriter(temp, false);
    writer.write("Hallo Wie gehts?");
    writer.close();// w  w w  . jav a  2s . co m
    return temp;
}

From source file:luceneprueba.utils.FileParser.java

static public void createFilesFromJSONArray() throws IOException {
    File dir = new File("files/input");
    File[] files = dir.listFiles();

    if (files == null) {
        System.out.println("No existe la carpeta \'input\' dentro de la carpeta files.");
        return;//from w  w w .ja v a  2  s  .com
    }

    if (files.length == 0) {
        System.out.println("No hay ningun archivo en la carpeta \'input\' para ser indexado");
        return;
    }

    BufferedReader br;
    String fileContent;
    JSONArray jsonArray = null;
    JSONParser jsonParser = new JSONParser();
    int i = 1;
    FileWriter datosReviews = null;
    try {
        datosReviews = new FileWriter("files/output/datos_reviews.txt");
    } catch (IOException ex) {
        ex.printStackTrace(System.out);
    }
    for (File file : files) {
        if (file.isFile() && file.canRead() && file.getName().endsWith(".txt")) {
            System.out.println("Leyendo el archivo: " + file.getName());
            FileWriter contentReviews;
            try {
                br = new BufferedReader(new FileReader(file));
                fileContent = br.readLine();
                jsonArray = (JSONArray) jsonParser.parse(fileContent);
                Iterator it = jsonArray.iterator();
                DecimalFormat formato = new DecimalFormat("000000");
                while (it.hasNext()) {
                    JSONObject json = (JSONObject) it.next();
                    if (json.get("Genre") != null && json.get("Date") != null) {
                        contentReviews = new FileWriter(
                                "files/output/clasificador/review_clasificador_" + formato.format(i) + ".txt");
                        datosReviews.write(Integer.toString(i) + "_" + (String) json.get("Date") + "_"
                                + (String) json.get("Genre") + "_" + (String) json.get("Score") + "\n");
                        contentReviews.write(Integer.toString(i) + " " + (String) json.get("Review"));
                        i++;
                        contentReviews.close();
                    }
                }
                br.close();
            } catch (FileNotFoundException ex) {
                ex.printStackTrace(System.out);
            } catch (IOException | ParseException ex) {
                ex.printStackTrace(System.out);
            }
        }
    }
    datosReviews.close();
}

From source file:com.ut.healthelink.service.CCDtoTxt.java

public String TranslateCCDtoTxt(String fileLocation, String ccdFileName, int orgId) throws Exception {

    Organization orgDetails = organizationmanager.getOrganizationById(orgId);
    fileSystem dir = new fileSystem();

    dir.setDir(orgDetails.getcleanURL(), "templates");

    String templatefileName = orgDetails.getparsingTemplate();

    URLClassLoader loader = new URLClassLoader(
            new URL[] { new URL("file://" + dir.getDir() + templatefileName) });

    // Remove the .class extension
    Class cls = loader.loadClass(templatefileName.substring(0, templatefileName.lastIndexOf('.')));
    Constructor constructor = cls.getConstructor();

    Object CCDObj = constructor.newInstance();

    Method myMethod = cls.getMethod("CCDtoTxt", new Class[] { File.class });

    /* Get the uploaded CCD File */
    fileLocation = fileLocation.replace("/Applications/bowlink/", "").replace("/home/bowlink/", "")
            .replace("/bowlink/", "");
    dir.setDirByName(fileLocation);/*from   w w  w.j a v a  2  s . c o  m*/

    File ccdFile = new File(dir.getDir() + ccdFileName + ".xml");

    /* Create the txt file that will hold the CCD fields */
    String newfileName = new StringBuilder()
            .append(ccdFile.getName().substring(0, ccdFile.getName().lastIndexOf("."))).append(".")
            .append("txt").toString();

    File newFile = new File(dir.getDir() + newfileName);

    if (newFile.exists()) {
        try {

            if (newFile.exists()) {
                int i = 1;
                while (newFile.exists()) {
                    int iDot = newfileName.lastIndexOf(".");
                    newFile = new File(dir.getDir() + newfileName.substring(0, iDot) + "_(" + ++i + ")"
                            + newfileName.substring(iDot));
                }
                newfileName = newFile.getName();
                newFile.createNewFile();
            } else {
                newFile.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        newFile.createNewFile();
        newfileName = newFile.getName();

    }

    FileWriter fw = new FileWriter(newFile, true);

    /* END */
    String fileRecords = (String) myMethod.invoke(CCDObj, new Object[] { ccdFile });

    fw.write(fileRecords);

    fw.close();

    return newfileName;

}

From source file:AIR.ResourceBundler.Console.ResourcesBuilder.java

private void writeAppend(FileWriter sw, FileSetInput fileInput) {
    if (!StringUtils.isBlank(fileInput.getAppend())) {
        try {/*from ww w  .  j a  va 2  s . c om*/
            sw.write(fileInput.getAppend());
        } catch (IOException e) {
        }
    }
}

From source file:AIR.ResourceBundler.Console.ResourcesBuilder.java

private void writePrepend(FileWriter sw, FileSetInput fileInput) {
    if (!StringUtils.isBlank(fileInput.getPrepend())) {
        try {/* w  w  w .  j ava  2  s .  c  o  m*/
            sw.write(fileInput.getPrepend());
        } catch (IOException e) {
        }
    }
}

From source file:de.uzk.hki.da.grid.CTIrodsCommandLineConnector.java

private void destroyTestFileOnLongTermStorage() throws IOException {
    File testFile = new File(testCollPhysicalPathOnLTA + "/urn.tar");
    FileWriter writer = new FileWriter(testFile, false);
    writer.write("Hallo Wie gehts? DESTROYED");
    writer.close();/*  w w  w  .  j  a v  a  2  s  . c om*/
}

From source file:fr.mcc.ginco.services.ThesaurusServiceImpl.java

@Transactional(readOnly = false)
@Override// w  ww  .j  ava2 s .  co m
public Thesaurus archiveThesaurus(Thesaurus thesaurus) {

    String fileContent = gincoThesaurusExportService.getThesaurusExport(thesaurus);
    File ready = new File(archivePath + thesaurus.getTitle().replaceAll("[^a-zA-Z0-9\\._]+", "_") + "_"
            + DateUtil.toString(DateUtil.nowDate()).replaceAll(" ", "_").replaceAll(":", "_") + ".xml");
    try {
        File checkPath = new File(archivePath);
        if (!checkPath.exists()) {
            FileUtils.forceMkdir(checkPath);
        }
        FileWriter writer = new FileWriter(ready);
        writer.write(fileContent);
        writer.flush();
        writer.close();

    } catch (IOException e) {
        throw new TechnicalException("Error writing file to path : " + publishPath, e);
    }

    thesaurus.setArchived(Boolean.TRUE);
    return thesaurusDAO.update(thesaurus);
}