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.applerox.jack.AppleCommands.AppleCommands.java

public static boolean resetConfigFile(File configFile, boolean deleteOld) {
    if (deleteOld && configFile.exists()) {
        configFile.delete();//from w w w.j a va2  s . c o m
        try {
            //createDefaultItems(configFile, defaults);
            return true;
        } catch (Exception e) {
            ac.logger
                    .severe("[AppleCommands] Failed to reset configuration! Let AppleCommands devs know this:");
            e.printStackTrace();
        }
    } else if (configFile.exists() && !deleteOld) {
        try {
            FileReader instream = new FileReader(configFile);
            FileWriter outstream = new FileWriter(configFile);
            BufferedReader reader = new BufferedReader(instream);
            BufferedWriter writer = new BufferedWriter(outstream);

            //for (line : reader.getLines()) {
            //   li
            //}

            instream.close();
            outstream.close();
        } catch (Exception e) {
            ac.logger
                    .severe("[AppleCommands] Failed to reset configuration! Let AppleCommands devs know this!");
            e.printStackTrace();
        }
    } else if (!configFile.exists()) {
        try {
            configFile.createNewFile();
        } catch (Exception e) {
            ac.logger.severe(
                    "[AppleCommands] Failed to create configuration file! Let AppleCommands devs know this!");
        }

    }

    return true;
}

From source file:com.ikon.dao.HibernateUtil.java

/**
 * Generate database schema and initial data for a defined dialect
 */// ww  w  .j  a  va 2 s  .c om
public static void generateDatabase(String dialect) throws IOException {
    // Configure Hibernate
    log.info("Exporting Database Schema...");
    String dbSchema = EnvironmentDetector.getUserHome() + "/schema.sql";
    Configuration cfg = getConfiguration().configure();
    cfg.setProperty("hibernate.dialect", dialect);
    SchemaExport se = new SchemaExport(cfg);
    se.setOutputFile(dbSchema);
    se.setDelimiter(";");
    se.setFormat(false);
    se.create(false, false);
    log.info("Database Schema exported to {}", dbSchema);

    String initialData = new File("").getAbsolutePath() + "/src/main/resources/default.sql";
    log.info("Exporting Initial Data from '{}'...", initialData);
    String initData = EnvironmentDetector.getUserHome() + "/data.sql";
    FileInputStream fis = new FileInputStream(initialData);
    String ret = DatabaseDialectAdapter.dialectAdapter(fis, dialect);
    FileWriter fw = new FileWriter(initData);
    IOUtils.write(ret, fw);
    fw.flush();
    fw.close();
    log.info("Initial Data exported to {}", initData);
}

From source file:bioLockJ.AppController.java

private static void markProjectComplete() throws Exception {
    final File f = new File(Config.requireExistingDirectory(Config.PROJECT_DIR).getAbsolutePath()
            + File.separator + Constants.BLJ_COMPLETE);
    final FileWriter writer = new FileWriter(f);
    writer.close();
    if (!f.exists()) {
        throw new Exception("Unable to create " + f.getAbsolutePath());
    }//ww  w.j av  a 2s  . c  o  m
}

From source file:com.wavemaker.commons.util.IOUtils.java

/**
 * Touch a file (see touch(1)). If the file doesn't exist, create it as an empty file. If it does exist, update its
 * modification time.//from   w  ww  .  ja v  a 2 s . c om
 *
 * @param f The File.
 * @throws IOException
 */
public static void touch(File f) throws IOException {

    if (!f.exists()) {
        FileWriter fw = new FileWriter(f);
        fw.close();
    } else {
        f.setLastModified(System.currentTimeMillis());
    }
}

From source file:com.yhfudev.SimulatorForSelfStabilizing.java

public static void main(String[] args) {
    // command line lib: apache CLI http://commons.apache.org/proper/commons-cli/
    // command line arguments:
    //  -- input file
    //  -- output line to a csv file
    //  -- algorithm: Ding's linear or randomized

    // single thread parsing ...
    Options options = new Options();
    options.addOption("h", false, "print this message");
    //heuristic//from  w w w  . j a va2 s.c  o m
    options.addOption("u", false, "(rand) heuristic on");
    options.addOption("y", true, "show the graph with specified delay (ms)");
    options.addOption("i", true, "the input file name");
    options.addOption("o", true, "the results is save to a attachable output cvs file");
    options.addOption("l", true, "the graph activities trace log file name");
    options.addOption("s", true, "save the graph to a file");
    options.addOption("a", true, "the algorithm name, ding or rand");
    // options specified to generator
    options.addOption("g", true,
            "the graph generator algorithm name: fan1l, fan2l, rand, doro, flower, watt, lobster");
    options.addOption("n", true, "the number of nodes");
    options.addOption("d", true, "(rand) the node degree (max)");
    options.addOption("f", false, "(rand) if the degree value is fix or not");
    options.addOption("p", true, "(watt) the probability of beta");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        e.printStackTrace();
        return;
    }
    if (cmd.hasOption("h")) {
        showHelp(options);
        return;
    }

    int delay_time = 0;
    if (cmd.hasOption("y")) {
        delay_time = Integer.parseInt(cmd.getOptionValue("y"));
    }

    String sFileName = null;
    sFileName = null;
    FileWriter writer = null;
    if (cmd.hasOption("o")) {
        sFileName = cmd.getOptionValue("o");
    }
    if ((null != sFileName) && (!"".equals(sFileName))) {
        try {
            writer = new FileWriter(sFileName, true); // true: append
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Error: unable to open the output file " + sFileName);
            return;
        }
    }
    FileWriter wrGraph = null;
    sFileName = null;
    if (cmd.hasOption("s")) {
        sFileName = cmd.getOptionValue("s");
    }
    if ((null != sFileName) && (!"".equals(sFileName))) {
        try {
            wrGraph = new FileWriter(sFileName, true); // true: append
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Error: unable to open the saveGraph file " + sFileName);
            return;
        }
    }

    sFileName = null;
    if (cmd.hasOption("i")) {
        sFileName = cmd.getOptionValue("i");
    }
    String genname = null;
    if (cmd.hasOption("g")) {
        genname = cmd.getOptionValue("g");
    }
    if ((null == genname) && (null == sFileName)) {
        System.out.println("Error: not specify the input file or graph generator");
        showHelp(options);
        return;
    }
    if ((null != genname) && (null != sFileName)) {
        System.out.println("Error: do not specify the input file and graph generator at the same time");
        showHelp(options);
        return;
    }

    if (delay_time > 0) {
        // create and display a graph
        System.setProperty("org.graphstream.ui.renderer", "org.graphstream.ui.j2dviewer.J2DGraphRenderer");
    }

    Graph graph = new SingleGraph("test");
    //graph.setNullAttributesAreErrors(true); // to throw an exception instead of returning null (in getAttribute()).
    if (delay_time > 0) {
        graph.addAttribute("ui.quality");
        graph.addAttribute("ui.antialias");
        graph.addAttribute("ui.stylesheet", "url(data/selfstab-mwcds.css);");
        graph.display();
    }

    // save the trace to file
    FileSinkDGS dgs = null;
    if (cmd.hasOption("l")) {
        dgs = new FileSinkDGS();
        graph.addSink(dgs);
        try {
            dgs.begin(cmd.getOptionValue("l"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Generator generator = null;
    if (null != sFileName) {
        System.out.println("DEBUG: the input file=" + sFileName);
        FileSource source = new FileSourceDGS();
        source.addSink(graph);
        int count_edge_error = 0;
        try {
            //source.begin("data/selfstab-mwcds.dgs"); // Ding's paper example
            //source.begin("data/selfstab-ds.dgs");    // DS example
            //source.begin("data/selfstab-doro-1002.dgs"); // DorogovtsevMendes
            //source.begin("data/selfstab-rand-p10-10002.dgs"); // random connected graph with degree = 10% nodes
            //source.begin("data/selfstab-rand-f5-34.dgs"); // random connected graph with degree = 5
            source.begin(sFileName);
            while (true) {
                try {
                    if (false == source.nextEvents()) {
                        break;
                    }
                } catch (EdgeRejectedException e) {
                    // ignore
                    count_edge_error++;
                    System.out.println("DEBUG: adding edge error: " + e.toString());
                }
                if (delay_time > 0) {
                    delay(delay_time);
                }
            }
            source.end();
            //} catch (InterruptedException e) {
            //    e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("DEBUG: END read from source. # of edges ignored=" + count_edge_error);
    } else {
        // assert (genname != null);

        // graph generator
        //generator = new ChvatalGenerator(); // fix size
        //generator = new FullGenerator(); // full connected, 2 steps,1 node in dominate set
        //generator = new GridGenerator(); // only one result
        //generator = new HypercubeGenerator(); // one result
        //generator = new IncompleteGridGenerator(); // error
        //generator = new PetersenGraphGenerator(); // fix size
        //generator = new PointsOfInterestGenerator(); // error
        //generator = new RandomEuclideanGenerator(); // linear algo endless loop
        //generator = new RandomFixedDegreeDynamicGraphGenerator(); //
        //generator = new RandomGenerator(); //
        //generator = new URLGenerator("http://www.cnbeta.com"); //
        //generator = new WikipediaGenerator("Antarctica"); // no end

        //generator = new DorogovtsevMendesGenerator(); // ok
        //generator = new FlowerSnarkGenerator(); // ok
        //generator = new WattsStrogatzGenerator(maxSteps, 30, 0.5); // small world, ok
        //generator = new LobsterGenerator(); // tree like, ok

        int i;
        int n = 12; // the number of nodes
        if (cmd.hasOption("n")) {
            n = Integer.parseInt(cmd.getOptionValue("n"));
        }
        int d = 3; // the degree of nodes
        if (cmd.hasOption("d")) {
            d = Integer.parseInt(cmd.getOptionValue("d"));
        }
        boolean isFix = false;
        if (cmd.hasOption("f")) {
            isFix = true;
        }
        if ("".equals(genname)) {
            System.out.println("Error: not set generator name");
            return;
        } else if ("fan1l".equals(genname)) {
            generator = new FanGenerator();
        } else if ("fan2l".equals(genname)) {
            generator = new Fan2lGenerator(graph, d);
        } else if ("doro".equals(genname)) {
            generator = new DorogovtsevMendesGenerator();
        } else if ("flower".equals(genname)) {
            generator = new FlowerSnarkGenerator();
        } else if ("lobster".equals(genname)) {
            generator = new LobsterGenerator();
        } else if ("rand".equals(genname)) {
            generator = new ConnectionGenerator(graph, d, false, isFix);
        } else if ("watt".equals(genname)) {
            // WattsStrogatzGenerator(n,k,beta)
            // a ring of n nodes
            // each node is connected to its k nearest neighbours, k must be even
            // n >> k >> log(n) >> 1
            // beta being a probability it must be between 0 and 1.
            int k;
            double beta = 0.5;
            if (cmd.hasOption("p")) {
                beta = Double.parseDouble(cmd.getOptionValue("p"));
            }
            k = (n / 20) * 2;
            if (k < 2) {
                k = 2;
            }
            if (n < 2 * 6) {
                n = 2 * 6;
            }
            generator = new WattsStrogatzGenerator(n, k, beta);
        }
        /*int listf5[][] = {
        {12, 5},
        {34, 5},
        {102, 5},
        {318, 5},
        {1002, 5},
        {3164, 5},
        {10002, 5},
        };
        int listp3[][] = {
        {12, 2},
        {34, 2},
        {102, 3},
        {318, 9},
        {1002, 30},
        {3164, 90},
        {10002, 300},
        };
        int listp10[][] = {
        {12, 2},
        {34, 3},
        {102, 10},
        {318, 32},
        {1002, 100},
        {3164, 316},
        {10002, 1000},
        };
        i = 6;
        maxSteps = listf5[i][0];
        int degree = listf5[i][1];
        generator = new ConnectionGenerator(graph, degree, false, true);
        */
        generator.addSink(graph);
        generator.begin();
        for (i = 1; i < n; i++) {
            generator.nextEvents();
        }
        generator.end();
        delay(500);
    }

    if (cmd.hasOption("a")) {
        SinkAlgorithm algorithm = null;
        String algo = "rand";
        algo = cmd.getOptionValue("a");
        if ("ding".equals(algo)) {
            algorithm = new SelfStabilizingMWCDSLinear();
        } else if ("ds".equals(algo)) {
            algorithm = new SelfStabilizingDSLinear();
        } else {
            algorithm = new SelfStabilizingMWCDSRandom();
        }
        algorithm.init(graph);
        algorithm.setSource("0");
        if (delay_time > 0) {
            algorithm.setAnimationDelay(delay_time);
        }
        if (cmd.hasOption("u")) {
            algorithm.heuristicOn(true);
        } else {
            algorithm.heuristicOn(false);
        }
        algorithm.compute();

        GraphVerificator verificator = new MWCDSGraphVerificator();
        if (verificator.verify(graph)) {
            System.out.println("DEBUG: PASS MWCDSGraphVerificator verficiation.");
        } else {
            System.out.println("DEBUG: FAILED MWCDSGraphVerificator verficiation!");
        }

        if (null != writer) {
            AlgorithmResult result = algorithm.getResult();
            result.SaveTo(writer);
            try {
                writer.flush();
                writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        algorithm.terminate();
    }

    if (null != generator) {
        generator.removeSink(graph);
    }
    if (dgs != null) {
        graph.removeSink(dgs);
        try {
            dgs.end();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (null != wrGraph) {
        try {
            saveGraph(graph, wrGraph);
            wrGraph.flush();
            wrGraph.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java

public static void dumpToFile(String dest, String content) throws IOException {
    FileWriter writer = new FileWriter(dest);
    writer.write(content);/*  ww  w. j  ava 2  s. c om*/
    writer.close();
}

From source file:com.me.edu.Servlet.ElasticSearch_Backup.java

public static String getSentence(String input) {
    String paragraph = input;/*  ww w  . j  av a 2s  .c  o  m*/
    Reader reader = new StringReader(paragraph);
    DocumentPreprocessor dp = new DocumentPreprocessor(reader);
    List<String> sentenceList = new ArrayList<String>();

    for (List<HasWord> sentence : dp) {
        String sentenceString = Sentence.listToString(sentence);
        sentenceList.add(sentenceString.toString());
    }
    String sent = "";
    for (String sentence : sentenceList) {
        System.out.println(sentence);
        sent = sent + " " + sentence + "\n";
    }
    try {

        FileWriter file = new FileWriter("Sentences.txt");
        file.write(sent.toString());
        file.flush();
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return sent;
}

From source file:net.sourceforge.jcctray.utils.ObjectPersister.java

public static void saveCruiseRegistry(CruiseRegistry registry, FileWriter writer) throws IOException {
    try {//from  w w  w . java 2s.  c  om
        writer.write("<?xml version='1.0' ?>\n");
        writer.write("<cruiseregistry>\n");
        writer.write("   <cruiseImpls>\n");
        saveCruiseImpls(writer, registry.getCruiseImpls());
        writer.write("   </cruiseImpls>\n");
        writer.write("</cruiseregistry>\n");
    } catch (IOException e) {
        throw e;
    } finally {
        writer.close();
    }
}

From source file:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java

/** Save data to a file.
 * @param dirName The full directory name
 * @param fileName The base name of the file to create
 * @param format The format to use; a key in
 *  ToolkitConfig.FORMAT_TO_FILEEXT_MAP.
 * @param data The data to be written/*  www  . j av a2  s.c o  m*/
 * @return The complete, full path to the file.
 */
public static String saveFile(final String dirName, final String fileName, final String format,
        final String data) {
    String fileExtension = ToolkitConfig.FORMAT_TO_FILEEXT_MAP.get(format.toLowerCase());
    String filePath = dirName + File.separator + fileName + fileExtension;
    FileWriter writer = null;
    try {
        requireDirectory(dirName);
        File oFile = new File(filePath);
        writer = new FileWriter(oFile);
        writer.write(data);
        writer.close();
    } catch (IOException e) {
        return "Exception: " + e.toString();
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                return "Exception: " + e.toString();
            }
        }
    }
    return filePath;
}

From source file:bioLockJ.AppController.java

/**
 * If user prop indicates they need a copy of the input files, copy them to the project dir.
 *
 * @throws Exception//from w ww .  j a  va  2 s  .c  o  m
 */
private static void copyInputDirs(final File targetDir) throws Exception {

    if ((targetDir == null) || !targetDir.isDirectory()) {
        throw new Exception("Unable to copy input files.  Parameter \"targetDir\" is not a directory: "
                + ((targetDir == null) ? "null" : targetDir.getAbsolutePath()));
    }

    final File startedFlag = new File(targetDir.getAbsolutePath() + File.separator + Constants.BLJ_STARTED);
    if (startedFlag.exists()) {
        recursiveFileDelete(targetDir);
    }

    if (!targetDir.exists()) {
        targetDir.mkdirs();
    }

    for (final File dir : Config.requireExistingDirectories(Config.INPUT_DIRS)) {
        Log.out.info("Copying input files from " + dir + " to " + targetDir);
        FileUtils.copyDirectory(dir, targetDir);
    }

    final File completeFlag = new File(targetDir.getAbsolutePath() + File.separator + Constants.BLJ_COMPLETE);
    final FileWriter writer = new FileWriter(completeFlag);
    writer.close();
    if (!completeFlag.exists()) {
        throw new Exception("Unable to create " + completeFlag.getAbsolutePath());
    }
}