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:org.psidnell.omnifocus.model.RawData.java

public static void exportRawData(RawData rawData, File file) throws IOException {

    try (Writer out = new FileWriter(file)) {
        OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValue(out, rawData);
    }/* w w w .j  a  va2 s.c  o m*/
}

From source file:Utilitarios.Imprimir.java

public void imprimirGrafico(Image image) throws IOException {

    FileWriter arq = new FileWriter("D:\\Orcamentos\\Grafico.doc");//cria o arquivo
    PrintWriter gravarArq = new PrintWriter(arq);

    gravarArq.println("Oramento Banzos Instituto de Msica "); //linha de conteudo do txt
    gravarArq.println(" ");
    gravarArq.println(image);/*from ww  w .  j a  v a  2 s .  co m*/

    arq.close();

}

From source file:org.springframework.rest.documentation.doclet.RestDoclet.java

public static boolean start(RootDoc rootDoc) throws IOException {

    Javadoc api = new JavadocProcessor().process(rootDoc);

    File outputDirectory = getOutputDirectory(rootDoc.options());

    if (!outputDirectory.isDirectory() && !outputDirectory.mkdirs()) {
        throw new IllegalStateException("Failed to create output directory " + outputDirectory);
    }//  w  w w  .  j  a v a2 s .com

    File file = new File(outputDirectory, "javadoc.json");

    FileWriter writer = new FileWriter(file);

    JsonGenerator generator = new JsonFactory(new ObjectMapper()).createGenerator(writer)
            .useDefaultPrettyPrinter();

    generator.writeObject(api);

    return true;
}

From source file:it.unibas.spicybenchmark.persistence.DAOLogFile.java

public static void saveLog(String log, String logFile) throws DAOException {
    BufferedWriter writer = null;
    try {/*  w w  w. ja v  a 2  s.c om*/
        File f = new File(logFile);
        f.getParentFile().mkdirs();
        FileWriter fileWriter = new FileWriter(logFile);
        writer = new BufferedWriter(fileWriter);
        writer.write(log);
    } catch (FileNotFoundException fnfe) {
        throw new DAOException(" File not found: " + fnfe);
    } catch (IOException ioe) {
        throw new DAOException(" Error: " + ioe);
    } catch (NoSuchElementException nse) {
        throw new DAOException(" Error in file format: " + nse);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException ioe) {
        }
    }
}

From source file:com.fbartnitzek.tasteemall.data.csv.CsvFileWriter.java

public static String writeFile(String[] headers, List<List<String>> entries, File file) {

    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;//from ww w .j ava 2s  .c  o  m
    String msg = null;
    try {
        fileWriter = new FileWriter(file); //initialize FileWriter object
        csvFilePrinter = new CSVPrinter(fileWriter, CSV_FORMAT_RFC4180); //initialize CSVPrinter object
        csvFilePrinter.printRecord(Arrays.asList(headers)); //Create CSV file header

        //Write a new student object list to the CSV file
        for (List<String> dataEntry : entries) {
            csvFilePrinter.printRecord(dataEntry);
        }

    } catch (Exception e) {
        e.printStackTrace();
        msg = "Error in CsvFileWriter !!!";
    } finally {
        try {
            if (fileWriter != null) {
                fileWriter.flush();
                fileWriter.close();
            }
            if (csvFilePrinter != null) {
                csvFilePrinter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            msg = "Error while flushing/closing fileWriter/csvPrinter !!!";

        }
    }
    return msg;
}

From source file:model.Post_store.java

public static void add_post(String title, String content) {

    JSONObject obj = new JSONObject();
    obj.put("title", title);
    obj.put("content", content);

    JSONArray comments = new JSONArray();

    obj.put("comments", comments);

    JSONArray UA_comments = new JSONArray();

    obj.put("UA_comments", UA_comments);

    int lastid = getlastid();

    obj.put("id", lastid);

    try (FileWriter file = new FileWriter(root + "posts/" + lastid + ".json");) {
        file.write(obj.toJSONString());/*from   w ww .j  av a2 s  .c  o  m*/
        file.flush();
        file.close();

    } catch (IOException e) {
        System.out.println(e);
    }

    lastid++;

    setlastid(lastid);

    //System.out.print(obj);

}

From source file:msuresh.raftdistdb.RaftCluster.java

public static void createDefaultGlobal() throws IOException {
    JSONObject obj = new JSONObject();
    obj.put("currentCount", 5000);
    try (FileWriter file = new FileWriter(Constants.STATE_LOCATION + "global.info")) {
        file.write(obj.toJSONString());//from ww w . j  a  v a  2 s.c  o  m
    }
}

From source file:apps.ParsedPost.java

public static void main(String args[]) {

    Options options = new Options();

    options.addOption(INPUT_PARAM, null, true, INPUT_DESC);
    options.addOption(OUTPUT_PARAM, null, true, OUTPUT_DESC);
    options.addOption(MAX_NUM_REC_PARAM, null, true, MAX_NUM_REC_DESC);
    options.addOption(DEBUG_PRINT_PARAM, null, false, DEBUG_PRINT_DESC);
    options.addOption(EXCLUDE_CODE_PARAM, null, false, EXCLUDE_CODE_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    HashMap<String, ParsedPost> hQuestions = new HashMap<String, ParsedPost>();

    try {/*w w w  .  j ava 2 s . c  o  m*/
        CommandLine cmd = parser.parse(options, args);

        String inputFile = cmd.getOptionValue(INPUT_PARAM);

        if (null == inputFile)
            Usage("Specify: " + INPUT_PARAM, options);

        String outputFile = cmd.getOptionValue(OUTPUT_PARAM);

        if (null == outputFile)
            Usage("Specify: " + OUTPUT_PARAM, options);

        InputStream input = CompressUtils.createInputStream(inputFile);
        BufferedWriter output = new BufferedWriter(new FileWriter(new File(outputFile)));

        int maxNumRec = Integer.MAX_VALUE;

        String tmp = cmd.getOptionValue(MAX_NUM_REC_PARAM);

        if (tmp != null)
            maxNumRec = Integer.parseInt(tmp);

        boolean debug = cmd.hasOption(DEBUG_PRINT_PARAM);

        boolean excludeCode = cmd.hasOption(EXCLUDE_CODE_PARAM);

        System.out.println("Processing at most " + maxNumRec + " records, excluding code? " + excludeCode);

        XmlIterator xi = new XmlIterator(input, ROOT_POST_TAG);

        String elem;

        output.write("<?xml version='1.0' encoding='UTF-8'?><ystfeed>\n");

        for (int num = 1; num <= maxNumRec && !(elem = xi.readNext()).isEmpty(); ++num) {
            ParsedPost post = null;
            try {
                post = parsePost(elem, excludeCode);

                if (!post.mAcceptedAnswerId.isEmpty()) {
                    hQuestions.put(post.mId, post);
                } else if (post.mpostIdType.equals("2")) {
                    String parentId = post.mParentId;
                    String id = post.mId;
                    if (!parentId.isEmpty()) {
                        ParsedPost parentPost = hQuestions.get(parentId);
                        if (parentPost != null && parentPost.mAcceptedAnswerId.equals(id)) {
                            output.write(createYahooAnswersQuestion(parentPost, post));
                            hQuestions.remove(parentId);
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("Error parsing record # " + num + ", error message: " + e);
            }
            if (debug) {
                System.out.println(String.format("%s parentId=%s acceptedAnswerId=%s type=%s", post.mId,
                        post.mParentId, post.mAcceptedAnswerId, post.mpostIdType));
                System.out.println("================================");
                if (!post.mTitle.isEmpty()) {
                    System.out.println(post.mTitle);
                    System.out.println("--------------------------------");
                }
                System.out.println(post.mBody);
                System.out.println("================================");
            }
        }

        output.write("</ystfeed>\n");

        input.close();
        output.close();

    } catch (ParseException e) {
        Usage("Cannot parse arguments", options);
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

}

From source file:com.chargebee.MethodBank.MethodBank.java

public static CSVPrinter printerInitializer(String csvOut) throws IOException, Exception {
    CSVPrinter printer = new CSVPrinter(new FileWriter(csvOut),
            CSVFormat.EXCEL.withRecordSeparator("\n").withDelimiter(','));
    return printer;
}

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. jav a 2  s.  c  om*/
    }

    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();
}