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:com.devdungeon.httpexamples.DownloadFile.java

private static void download(String url, String filepath) {
    HttpClient client = new DefaultHttpClient();

    HttpParams params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 1000 * 5);
    HttpConnectionParams.setSoTimeout(params, 1000 * 5);

    HttpGet request = new HttpGet(url);

    HttpResponse response = null;// w  ww . ja v  a2 s.c o  m
    try {
        response = client.execute(request);
    } catch (IOException ex) {
        Logger.getLogger(HttpGetExample.class.getName()).log(Level.SEVERE, null, ex);
    }
    BufferedReader rd;
    String line = null;
    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        FileWriter fileWriter = new FileWriter(filepath);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        while ((line = rd.readLine()) != null) {
            bufferedWriter.write(line);
            bufferedWriter.newLine();
        }
        bufferedWriter.close();

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

From source file:edu.cmu.lti.oaqa.knn4qa.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(CommonParams.MAX_NUM_REC_PARAM, null, true, CommonParams.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 {/*from  ww  w  .j  a va2  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(CommonParams.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.monpie.histogram.RandomizeArray.java

public RandomizeArray() throws IOException {
    fileWriter = new FileWriter("random.txt");
}

From source file:com.sec.ose.osi.util.tools.FileOperator.java

public static boolean saveFile(String filePath, String contents) {

    File writeFile = new File(filePath);

    PrintWriter writer = null;/*from   www. j  a  va  2 s.c om*/

    try {
        writer = new PrintWriter(new FileWriter(writeFile));
        writer.println(contents);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        log.warn(e);
        return false;
    } finally {

        if (writer != null) {
            writer.flush();
            writer.close();
        }
        writer = null;
    }

    return true;
}

From source file:gov.nih.nci.restgen.util.GeneratorUtil.java

public static void writeFile(String _outputDir, String _fileName, String _content) {
    BufferedWriter bufferedWriter = null;

    try {//  ww  w . j  ava  2  s  .co  m
        createOutputDir(_outputDir);
        File file = new File(_outputDir, _fileName);
        FileWriter fileWriter = new FileWriter(file);
        bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(_content);
        bufferedWriter.flush();
    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        if (bufferedWriter != null) {
            try {
                bufferedWriter.close();
            } catch (Throwable t) {
            }
        }
    }
}

From source file:mrdshinse.sql2xlsx.util.FileUtil.java

public static File create(File file, String str) {
    try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)))) {
        pw.print(str);/*from   w ww. j a  v a2 s  . c  o  m*/
    } catch (IOException ex) {
        return file;
    }
    return file;
}

From source file:com.amazon.dtasdk.v2.signature.CredentialStoreTest.java

@BeforeClass
public static void setUp() throws IOException {
    VALID_FILE = File.createTempFile("store", "csv");
    FileWriter writer = new FileWriter(VALID_FILE);

    writer.write(String.format("%s %s\n", KEYS[0], KEYS[1]));
    // Intentionally check if blank lines are supported
    writer.write(String.format("%s %s\n\n", KEYS[2], KEYS[3]));
    writer.write(String.format("%s %s\n", KEYS[4], KEYS[5]));
    writer.write("\n");

    writer.close();//  w  w w .j a va  2 s .co  m

    INVALID_FILE = File.createTempFile("store", "csv");
    writer = new FileWriter(INVALID_FILE);

    writer.write(String.format("%s%s\n", KEYS[0], KEYS[1]));
    writer.write(String.format("%s %s\n", KEYS[2], KEYS[3]));
    writer.write(String.format("%s %s\n", KEYS[4], KEYS[5]));
    writer.write("\n");

    writer.close();
}

From source file:jsonconverter.createandwrite.JSONFileWriter.java

public void createFile(String name, String JSONFolderPath) {
    try {/* ww w .  ja v a  2  s .  c o m*/
        File file = new File(JSONFolderPath, name + ".txt");
        file.createNewFile();
        FileWriter fw = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(obj.toString());
        bw.flush();
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

public static String writeBytesToFile(String filePath, String content) {
    String path = "";
    try {/*w  w w .  ja v a 2 s .  co 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:br.edimarmanica.weir2.rule.type.RulesDataTypeController.java

/**
 * Persiste the datatype of each rule/*from w ww  .j ava 2s .  co  m*/
 *
 * @param site
 */
public static void persiste(Site site) {
    Map<String, DataType> ruleType = new HashMap<>();

    File dirInput = new File(Paths.PATH_INTRASITE + "/" + site.getPath() + "/extracted_values");
    for (File rule : dirInput.listFiles()) {
        ruleType.put(rule.getName(), RuleDataType.getMostFrequentType(rule));
    }

    File dirOutput = new File(Paths.PATH_WEIR_V2 + "/" + site.getPath());
    dirOutput.mkdirs();

    File file = new File(dirOutput.getAbsolutePath() + "/types.csv");
    String[] HEADER = { "RULE", "TYPE" };
    CSVFormat format = CSVFormat.EXCEL.withHeader(HEADER);

    try (Writer out = new FileWriter(file)) {
        try (CSVPrinter csvFilePrinter = new CSVPrinter(out, format)) {
            for (String rule : ruleType.keySet()) {
                List<String> dataRecord = new ArrayList<>();
                dataRecord.add(rule);
                dataRecord.add(ruleType.get(rule).name());
                csvFilePrinter.printRecord(dataRecord);
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(RulesDataTypeController.class.getName()).log(Level.SEVERE, null, ex);
    }
}