Example usage for java.io FileWriter close

List of usage examples for java.io FileWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:com.tomgibara.cluster.CreateGaussianMouse.java

public static void main(String[] args) throws IOException {
    GaussianRandomGenerator gen = new GaussianRandomGenerator(new JDKRandomGenerator());
    FileWriter writer = new FileWriter("R/gmouse.txt");
    try {/*from  www. j  a  va 2  s  . c o  m*/
        writeCluster(gen, new double[] { 0, 0 }, new double[] { 4, 4 }, 100, writer);
        writeCluster(gen, new double[] { -4, 4 }, new double[] { 2, 2 }, 50, writer);
        writeCluster(gen, new double[] { 4, 4 }, new double[] { 2, 2 }, 50, writer);
    } finally {
        writer.close();
    }
}

From source file:com.tomgibara.cluster.CreateUniformMouse.java

public static void main(String[] args) throws IOException {
    UniformRandomGenerator gen = new UniformRandomGenerator(new JDKRandomGenerator());
    FileWriter writer = new FileWriter("R/umouse.txt");
    try {//from   w  w  w  .j  a va 2s  .com
        writeCluster(gen, new double[] { 0, 0 }, new double[] { 4, 4 }, 300, writer);
        writeCluster(gen, new double[] { -4, 4 }, new double[] { 2, 2 }, 100, writer);
        writeCluster(gen, new double[] { 4, 4 }, new double[] { 2, 2 }, 100, writer);
    } finally {
        writer.close();
    }
}

From source file:com.qwazr.utils.HtmlUtils.java

public static void main(String args[]) throws IOException {
     if (args != null && args.length == 2) {
         List<String> lines = FileUtils.readLines(new File(args[0]));
         FileWriter fw = new FileWriter(new File(args[1]));
         PrintWriter pw = new PrintWriter(fw);
         for (String line : lines)
             pw.println(StringEscapeUtils.unescapeHtml4(line));
         pw.close();/*  ww  w  .ja v  a2s. c  om*/
         fw.close();
     }
     String text = "file://&shy;Users/ekeller/Moteur/infotoday_enterprisesearchsourcebook08/Open_on_Windows.exe";
     System.out.println(htmlWrap(text, 20));
     System.out.println(htmlWrapReduce(text, 20, 80));
     String url = "file://Users/ekeller/Moteur/infotoday_enterprisesearchsourcebook08/Open_on_Windows.exe?test=2";
     System.out.println(urlHostPathWrapReduce(url, 80));
 }

From source file:test1.ApacheHttpRestClient2.java

public final static void main(String[] args) {

    HttpClient httpClient = new DefaultHttpClient();
    try {/*from  w w w .  j av  a  2  s  .c o  m*/
        // this ona api call returns results in a JSON format
        HttpGet httpGetRequest = new HttpGet("https://api.ona.io/api/v1/users");

        // Execute HTTP request
        HttpResponse httpResponse = httpClient.execute(httpGetRequest);

        System.out.println("------------------HTTP RESPONSE----------------------");
        System.out.println(httpResponse.getStatusLine());
        System.out.println("------------------HTTP RESPONSE----------------------");

        // Get hold of the response entity
        HttpEntity entity = httpResponse.getEntity();

        // If the response does not enclose an entity, there is no need
        // to bother about connection release
        byte[] buffer = new byte[1024];
        if (entity != null) {
            InputStream inputStream = entity.getContent();
            try {
                int bytesRead = 0;
                BufferedInputStream bis = new BufferedInputStream(inputStream);
                while ((bytesRead = bis.read(buffer)) != -1) {
                    String chunk = new String(buffer, 0, bytesRead);
                    FileWriter file = new FileWriter("C:\\Users\\fred\\Desktop\\webicons\\output.txt");
                    //file.write(chunk.toJSONString());
                    file.write(chunk.toCharArray());
                    file.flush();
                    file.close();

                    System.out.print(chunk);
                    System.out.println(chunk);
                }
            } catch (IOException ioException) {
                // In case of an IOException the connection will be released
                // back to the connection manager automatically
                ioException.printStackTrace();
            } catch (RuntimeException runtimeException) {
                // In case of an unexpected exception you may want to abort
                // the HTTP request in order to shut down the underlying
                // connection immediately.
                httpGetRequest.abort();
                runtimeException.printStackTrace();
            }
            //          try {
            //              FileWriter file = new FileWriter("C:\\Users\\fred\\Desktop\\webicons\\output.json");
            //                file.write(bis.toJSONString());
            //                file.flush();
            //                file.close();
            //
            //                System.out.print(bis);
            //          } catch (Exception e) {
            //          }

            finally {
                // Closing the input stream will trigger connection release
                try {
                    inputStream.close();
                } catch (Exception ignore) {
                }
            }
        }
    } catch (ClientProtocolException e) {
        // thrown by httpClient.execute(httpGetRequest)
        e.printStackTrace();
    } catch (IOException e) {
        // thrown by entity.getContent();
        e.printStackTrace();
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:net.orzo.App.java

/**
 *
 *///w  w w  .  j a  va 2 s.  c  om
public static void main(final String[] args) {
    final App app = new App();
    Logger log = null;
    CommandLine cmd;

    try {
        cmd = app.init(args);

        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(
                    "orzo [options] user_script [user_arg1 [user_arg2 [...]]]\n(to generate a template: orzo -t [file path])",
                    app.cliOptions);

        } else if (cmd.hasOption("v")) {
            System.out.printf("Orzo.js version %s\n", app.props.get("orzo.version"));

        } else if (cmd.hasOption("t")) {
            String templateSrc = new ResourceLoader().getResourceAsString("net/orzo/template1.js");

            File tplFile = new File(cmd.getOptionValue("t"));
            FileWriter tplWriter = new FileWriter(tplFile);
            tplWriter.write(templateSrc);
            tplWriter.close();

            File dtsFile = new File(
                    String.format("%s/orzojs.d.ts", new File(tplFile.getAbsolutePath()).getParent()));
            FileWriter dtsWriter = new FileWriter(dtsFile);
            String dtsSrc = new ResourceLoader().getResourceAsString("net/orzo/orzojs.d.ts");
            dtsWriter.write(dtsSrc);
            dtsWriter.close();

        } else if (cmd.hasOption("T")) {
            String templateSrc = new ResourceLoader().getResourceAsString("net/orzo/template1.js");
            System.out.println(templateSrc);

        } else {

            // Logger initialization
            if (cmd.hasOption("g")) {
                System.setProperty("logback.configurationFile", cmd.getOptionValue("g"));

            } else {
                System.setProperty("logback.configurationFile", "./logback.xml");
            }
            log = LoggerFactory.getLogger(App.class);
            if (cmd.hasOption("s")) { // Orzo.js as a REST and AMQP service
                FullServiceConfig conf = new Gson().fromJson(new FileReader(cmd.getOptionValue("s")),
                        FullServiceConfig.class);
                Injector injector = Guice.createInjector(new CoreModule(conf), new RestServletModule());
                HttpServer httpServer = new HttpServer(conf, new JerseyGuiceServletConfig(injector));
                app.services.add(httpServer);

                if (conf.getAmqpResponseConfig() != null) {
                    // response AMQP service must be initialized before receiving one
                    app.services.add(injector.getInstance(AmqpResponseConnection.class));
                }

                if (conf.getAmqpConfig() != null) {
                    app.services.add(injector.getInstance(AmqpConnection.class));
                    app.services.add(injector.getInstance(AmqpService.class));
                }

                if (conf.getRedisConf() != null) {
                    app.services.add(injector.getInstance(RedisStorage.class));
                }

                Runtime.getRuntime().addShutdownHook(new ShutdownHook(app));
                app.startServices();

            } else if (cmd.hasOption("d")) { // Demo mode
                final String scriptId = "demo";
                final SourceCode demoScript = SourceCode.fromResource(DEMO_SCRIPT);
                System.err.printf("Running demo script %s.", demoScript.getName());
                CmdConfig conf = new CmdConfig(scriptId, demoScript, null, cmd.getOptionValue("p", null));
                TaskManager tm = new TaskManager(conf);
                tm.startTaskSync(tm.registerTask(scriptId, new String[0]));

            } else if (cmd.getArgs().length > 0) { // Command line mode
                File userScriptFile = new File(cmd.getArgs()[0]);
                String optionalModulesPath = null;
                String[] inputValues;
                SourceCode userScript;

                // custom CommonJS modules path
                if (cmd.hasOption("m")) {
                    optionalModulesPath = cmd.getOptionValue("m");
                }

                if (cmd.getArgs().length > 0) {
                    inputValues = Arrays.copyOfRange(cmd.getArgs(), 1, cmd.getArgs().length);
                } else {
                    inputValues = new String[0];
                }

                userScript = SourceCode.fromFile(userScriptFile);
                CmdConfig conf = new CmdConfig(userScript.getName(), userScript, optionalModulesPath,
                        cmd.getOptionValue("p", null));
                TaskManager tm = new TaskManager(conf);
                String taskId = tm.registerTask(userScript.getName(), inputValues);
                tm.startTaskSync(taskId);
                if (tm.getTask(taskId).getStatus() == TaskStatus.ERROR) {
                    tm.getTask(taskId).getFirstError().getErrors().stream().forEach(System.err::println);
                }

            } else {
                System.err.println("Invalid parameters. Try -h for more information.");
                System.exit(1);
            }
        }

    } catch (Exception ex) {
        System.err.printf("Orzo.js crashed with error: %s\nSee the log for details.\n", ex.getMessage());
        if (log != null) {
            log.error(ex.getMessage(), ex);

        } else {
            ex.printStackTrace();
        }
    }
}

From source file:OldExtractor.java

/**
 * @param args the command line arguments
 *///from w  w w .j  av a 2 s .  c  o  m
public static void main(String[] args) {
    // TODO code application logic here
    String bingUrl = "https://api.datamarket.azure.com/Bing/Search/Web?$top=10&$format=Atom&Query=%27gates%27";
    //Provide your account key here.
    String accountKey = "ghTYY7wD6LpyxUO9VRR7e1f98WFhHWYERMcw87aQTqQ";
    //  String accountKey = "xqbCjT87/MQz25JWdRzgMHdPkGYnOz77IYmP5FUIgC8";

    byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
    String accountKeyEnc = new String(accountKeyBytes);

    try {
        URL url = new URL(bingUrl);
        URLConnection urlConnection = url.openConnection();

        urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
        InputStream inputStream = (InputStream) urlConnection.getContent();
        byte[] contentRaw = new byte[urlConnection.getContentLength()];
        inputStream.read(contentRaw);
        String content = new String(contentRaw);
        //System.out.println(content);
        try {
            File file = new File("Results.xml");
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(content);
            //fileWriter.write("a test");
            fileWriter.flush();
            fileWriter.close();

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

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {
            //System.out.println("here");
            //Using factory get an instance of document builder
            DocumentBuilder db = dbf.newDocumentBuilder();

            //parse using builder to get DOM representation of the XML file
            Document dom = db.parse("Results.xml");
            Element docEle = (Element) dom.getDocumentElement();

            //get a nodelist of elements

            NodeList nl = docEle.getElementsByTagName("d:Url");
            if (nl != null && nl.getLength() > 0) {
                for (int i = 0; i < nl.getLength(); i++) {

                    //get the employee element
                    Element el = (Element) nl.item(i);
                    // System.out.println("here");
                    System.out.println(el.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }
            NodeList n2 = docEle.getElementsByTagName("d:Title");
            if (n2 != null && n2.getLength() > 0) {
                for (int i = 0; i < n2.getLength(); i++) {

                    //get the employee element
                    Element e2 = (Element) n2.item(i);
                    // System.out.println("here");
                    System.out.println(e2.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }

            NodeList n3 = docEle.getElementsByTagName("d:Description");
            if (n3 != null && n3.getLength() > 0) {
                for (int i = 0; i < n3.getLength(); i++) {

                    //get the employee element
                    Element e3 = (Element) n3.item(i);
                    // System.out.println("here");
                    System.out.println(e3.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }

        } catch (SAXException se) {
            se.printStackTrace();
        } catch (ParserConfigurationException pe) {
            pe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

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

    //The content string is the xml/json output from Bing.

}

From source file:SentiWordNetDemoCode.java

public static void main(String[] args) throws IOException {
    if (args.length < 2) {
        System.err.println("Usage: java SentiWordNetDemoCode <pathToSentiWordNetFile>");
        return;// w w  w.  j  a v a 2 s.  c  om
    }

    String pathToSWN = args[0];
    SentiWordNetDemoCode sentiwordnet = new SentiWordNetDemoCode(pathToSWN);

    JSONObject js = new JSONObject(sentiwordnet.dictionary);
    FileWriter csv = null;
    try {
        csv = new FileWriter(args[1]);
        csv.write(js.toJSONString());
        System.out.println("error");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (csv != null) {
            csv.close();
        }
    }

    // System.out.println("good#a "+sentiwordnet.extract("good", "a"));
    // System.out.println("bad#a "+sentiwordnet.extract("bad", "a"));
    // System.out.println("blue#a "+sentiwordnet.extract("blue", "a"));
    // System.out.println("blue#n "+sentiwordnet.extract("blue", "n"));
}

From source file:TabFilter.java

public static void main(String args[]) throws Exception {
    FileReader fr = new FileReader(args[0]);
    BufferedReader br = new BufferedReader(fr);

    FileWriter fw = new FileWriter(args[1]);
    BufferedWriter bw = new BufferedWriter(fw);

    // Convert tab to space characters
    String s;//from   w  w w .  j  ava 2s. com
    while ((s = br.readLine()) != null) {
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '\t')
                c = ' ';
            bw.write(c);
        }
    }

    bw.flush();
    fr.close();
    fw.close();
}

From source file:com.tuplejump.stargate.util.CQLUnitD.java

public static void main(String[] args) throws Exception {
    Person[] persons = jsonMapper.readValue(is2, Person[].class);
    File file = new File("samples/sample-json.cql");
    FileWriter fileWriter = new FileWriter(file);
    for (Person person : persons) {
        fileWriter.write(person.toInsertString() + "\n");
    }/*from  w w w . java  2s  . com*/
    fileWriter.flush();
    fileWriter.close();
}

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

public static void main(String[] args) {
    try {//from   w  w  w. ja  v a  2 s .c o  m
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet getRequest = new HttpGet(
                "http://www.ebi.ac.uk/ols/api/ontologies/mod/terms/http%253A%252F%252Fpurl.obolibrary.org%252Fobo%252FMOD_00861/descendants?size=2002");
        getRequest.addHeader("accept", "application/json");

        HttpResponse 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 output;
        FileWriter fw = new FileWriter("./mod.json");
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            fw.write(output);
        }

        fw.close();
        httpClient.close();

    } catch (ClientProtocolException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();
    }

}