Example usage for java.io Writer close

List of usage examples for java.io Writer close

Introduction

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

Prototype

public abstract void close() throws IOException;

Source Link

Document

Closes the stream, flushing it first.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    String s = "<xmltag atr=value>tag data</xmltag>";
    FileWriter fr = new FileWriter(new File("a.txt"));
    Writer br = new BufferedWriter(fr);
    br.write(s);//w w w  . j  av a 2  s .c o  m
    br.close();
}

From source file:Main.java

License:asdf

public static void main(String[] argv) throws Exception {

    Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("outfilename"), "UTF8"));
    out.write("asdf");
    out.close();
}

From source file:Main.java

License:asdf

public static void main(String[] argv) throws Exception {

    Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("outfilename"), "8859_1"));
    out.write("asdf");
    out.close();
}

From source file:FileReaderWriterExample.java

public static void main(String[] args) throws Exception {

    Reader r = new FileReader("in.txt");
    Writer w = new FileWriter("out.txt");
    int c;//from   ww w  .j a  v  a2s.c  o  m
    while ((c = r.read()) != -1) {
        System.out.print((char) c);
        w.write(c);
    }
    r.close();
    w.close();
}

From source file:fm.last.peyote.cacti.PeyoteCactiLauncher.java

public static void main(String[] args) throws JAXBException, IOException {
    if (args.length < 2 || args.length > 3) {
        printUsage();//from www  . ja v  a  2  s .  c o  m
    }
    String name = args[0];
    String url = args[1];
    ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/peyote.xml");
    applicationContext.registerShutdownHook();
    try {
        InputData inputData = createInputData(args, applicationContext, name, url);
        PeyoteMarshaller marshaller = applicationContext.getBean(PeyoteMarshaller.class);
        marshaller.setInputData(inputData);
        log.info("Starting Peyote");
        File file = new File("datatemplate.xml");
        Writer outWriter = new FileWriter(file);
        marshaller.generateCactiDataTemplate(outWriter);
        outWriter.close();
        log.info("generated data template for '" + name + "' in " + file.getAbsolutePath());

        // file = new File("graphtemplate.xml");
        // outWriter = new FileWriter(file);
        // marshaller.generateCactiGraphTemplate(outWriter);
        // outWriter.close();
        // log.info("generated data template for '" + name + "' in " +
        // file.getAbsolutePath());

        log.info("Peyote finished.");
    } finally {
        applicationContext.close();
    }
}

From source file:fr.itinerennes.bundler.integration.onebusaway.GenerateStaticObaApiResults.java

public static void main(String[] args) throws IOException, GtfsException {

    final String url = args[0];
    final String key = args[1];
    final String gtfsFile = args[2];
    final String out = args[3].replaceAll("/$", "");

    final Map<String, String> agencyMapping = new HashMap<String, String>();
    agencyMapping.put("1", "2");
    final GtfsDao gtfs = GtfsUtils.load(new File(gtfsFile), agencyMapping);

    oba = new JsonOneBusAwayClient(new DefaultHttpClient(), url, key);
    gson = OneBusAwayGsonFactory.newInstance(true);

    final Calendar end = Calendar.getInstance();
    end.set(2013, 11, 22, 0, 0);/*from w  w w  .j  a  v  a  2 s  .c  o m*/

    final Calendar start = Calendar.getInstance();
    start.set(2013, 10, 4, 0, 0);

    final Calendar current = Calendar.getInstance();
    current.setTime(start.getTime());

    while (current.before(end) || current.equals(end)) {
        System.out.println(current.getTime());
        for (final Stop stop : gtfs.getAllStops()) {
            final String stopId = stop.getId().toString();
            final String dateDir = String.format("%04d/%02d/%02d", current.get(Calendar.YEAR),
                    current.get(Calendar.MONTH) + 1, current.get(Calendar.DAY_OF_MONTH));
            final String methodDir = String.format("%s/schedule-for-stop", out);

            final File outDir = new File(String.format("%s/%s", methodDir, dateDir));
            outDir.mkdirs();
            final File f = new File(outDir, String.format("%s.json", stopId));

            final StopSchedule ss = oba.getScheduleForStop(stopId, current.getTime());
            final String json = gson.toJson(ss);

            final Writer w = new PrintWriter(f);
            w.write(json);
            w.close();
        }
        current.add(Calendar.DAY_OF_MONTH, 1);
    }

    final File outDir = new File(String.format("%s/trip-details", out));
    outDir.mkdirs();
    for (final Trip trip : gtfs.getAllTrips()) {
        final String tripId = trip.getId().toString();
        final File f = new File(outDir, String.format("%s.json", tripId));

        final TripSchedule ts = oba.getTripDetails(tripId);
        final String json = gson.toJson(ts);

        final Writer w = new PrintWriter(f);
        w.write(json);
        w.close();
    }
}

From source file:net.ontopia.persistence.rdbms.DDLWriter.java

public static void main(String[] argv) throws Exception {

    // Initialize logging
    CmdlineUtils.initializeLogging();/*from   w w  w . j  ava2 s. c  om*/

    // Initialize command line option parser and listeners
    CmdlineOptions options = new CmdlineOptions("DDLWriter", argv);

    // Register logging options
    CmdlineUtils.registerLoggingOptions(options);

    // Parse command line options
    try {
        options.parse();
    } catch (CmdlineOptions.OptionsException e) {
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
    }

    // Get command line arguments
    String[] args = options.getArguments();
    if (args.length < 3) {
        System.err.println("Error: need exactly two files as arguments.");
        usage();
        System.exit(1);
    }

    String schema = args[0];
    String dbtype = args[1];
    String[] platforms = StringUtils.split(args[2], ",");
    String createfile = args[3];
    String dropfile = args[4];

    Project project = DatabaseProjectReader.loadProject(schema);

    GenericSQLProducer producer;
    switch (dbtype) {
    case "postgresql":
        producer = new PostgreSQLProducer(project, platforms);
        break;
    case "oracle":
        producer = new OracleSQLProducer(project, platforms);
        break;
    case "sqlserver":
        producer = new SQLServerSQLProducer(project, platforms);
        break;
    case "mysql":
        producer = new MySqlSQLProducer(project, platforms);
        break;
    case "db2":
        producer = new DB2SQLProducer(project, platforms);
        break;
    case "firebird":
        producer = new FirebirdSQLProducer(project, platforms);
        break;
    default:
        producer = new GenericSQLProducer(project, platforms);
        break;
    }

    // Generate create file
    Writer cwriter = new FileWriter(createfile);
    producer.writeCreate(cwriter);
    cwriter.close();

    // Generate create file
    Writer dwriter = new FileWriter(dropfile);
    producer.writeDrop(dwriter);
    dwriter.close();
}

From source file:testing01.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String outputFile = "test.html";
    String baseWebSite = "http://www.ettoday.net/news/20130802/250478.htm";
    try {/*www.  j  a va  2 s  . c  o m*/
        //HttpGet httpGet = new HttpGet(baseWebSite + "cat/politic/r");
        HttpGet httpGet = new HttpGet(baseWebSite);
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response
        // object
        // to allow the response content to be streamed directly from the
        // network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally
        // clause.
        // Please note that if response content is not fully consumed the
        // underlying
        // connection cannot be safely re-used and will be shut down and
        // discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            String responseString = EntityUtils.toString(entity1, "UTF-8");
            // System.out.println(responseString);
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF8"));
            out.write(responseString);
            out.close();
            EntityUtils.consume(entity1);
            System.out.println(baseWebSite + " output to " + outputFile + " successful");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            response1.close();
        }
        /*
         * HttpPost httpPost = new HttpPost("http://targethost/login"); List
         * <NameValuePair> nvps = new ArrayList <NameValuePair>();
         * nvps.add(new BasicNameValuePair("username", "vip")); nvps.add(new
         * BasicNameValuePair("password", "secret")); httpPost.setEntity(new
         * UrlEncodedFormEntity(nvps)); CloseableHttpResponse response2 =
         * httpclient.execute(httpPost);
         * 
         * try { System.out.println(response2.getStatusLine()); HttpEntity
         * entity2 = response2.getEntity(); // do something useful with the
         * response body // and ensure it is fully consumed
         * EntityUtils.consume(entity2); } finally { response2.close(); }
         */
    } finally {
        httpclient.close();
    }
}

From source file:net.morphbank.webclient.ProcessFiles.java

/**
 * @param args/*from   ww w  . ja va 2s  . co m*/
 *            args[0] directory including terminal '/' 
 *            args[1] prefix of request files 
 *            args[2] number of digits in file index value
 *            args[3] number of files 
 *            args[4] index of first file (default 0) 
 *            args[5] prefix of service 
 *            args[6] prefix of response files (default args[1] + "Resp")
 */
public static void main(String[] args) {
    ProcessFiles fileProcessor = new ProcessFiles();
    // restTest.processRequest(URL, UPLOAD_FILE);

    String zeros = "0000000";

    if (args.length < 4) {
        System.out.println("Too few parameters");
    } else {
        try {
            // get parameters
            String reqDir = args[0];
            String reqPrefix = args[1];
            int numDigits = Integer.valueOf(args[2]);
            if (numDigits > zeros.length())
                numDigits = zeros.length();
            NumberFormat intFormat = new DecimalFormat(zeros.substring(0, numDigits));
            int numFiles = Integer.valueOf(args[3]);
            int firstFile = 0;

            BufferedReader fileIn = new BufferedReader(new FileReader(FILE_IN_PATH));
            String line = fileIn.readLine();
            fileIn.close();
            firstFile = Integer.valueOf(line);
            // firstFile = 189;
            // numFiles = 1;
            int lastFile = firstFile + numFiles - 1;
            String url = URL;
            String respPrefix = reqPrefix + "Resp";
            if (args.length > 5)
                respPrefix = args[5];
            if (args.length > 6)
                url = args[6];

            // process files
            for (int i = firstFile; i <= lastFile; i++) {
                String xmlOutputFile = null;
                String requestFile = reqDir + reqPrefix + intFormat.format(i) + ".xml";
                System.out.println("Processing request file " + requestFile);
                String responseFile = reqDir + respPrefix + intFormat.format(i) + ".xml";
                System.out.println("Response file " + responseFile);
                // restTest.processRequest(URL, UPLOAD_FILE);
                fileProcessor.processRequest(url, requestFile, responseFile);
                Writer fileOut = new FileWriter(FILE_IN_PATH, false);
                fileOut.append(Integer.toString(i + 1));
                fileOut.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    String[] words = { "", "e", "a", "c" };
    Writer w = new BufferedWriter(new OutputStreamWriter(System.out, "Cp850"));
    for (int i = 0; i < 4; i++) {
        w.write(words[i] + " ");
    }/*from ww w.j  a va 2  s.  c  om*/
    Arrays.sort(words);
    for (int i = 0; i < 4; i++) {
        w.write(words[i] + " ");
    }
    w.flush();
    w.close();
}