Example usage for java.io FileWriter write

List of usage examples for java.io FileWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:CsvConverter.java

/**
 * DOCUMENT ME!//from   ww w. j a  va2s . c o  m
 *
 * @param fileName 
 */
public void writeToFile(String fileName) {
    try {
        FileWriter bwOut = new FileWriter(fileName);

        //write headers
        for (int i = 0; i < headers.length; i++) {
            bwOut.write(createCSVField(headers[i]));

            if (i != (headers.length - 1)) {
                bwOut.write(",");
            }
        }

        bwOut.write("\n");

        //write data
        for (int i = 0; i < data.size(); i++) {
            String[] dataArray = (String[]) data.get(i);

            for (int j = 0; j < dataArray.length; j++) {
                bwOut.write(createCSVField(dataArray[j]));

                if (j != (dataArray.length - 1)) {
                    bwOut.write(",");
                }
            }

            bwOut.write("\n");
        }

        bwOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.ala.spatial.web.services.SitesBySpeciesWSControllerTabulated.java

private void initListProperties() throws IOException {
    //create a list.properties if it does not exist
    String pth = AlaspatialProperties.getAnalysisWorkingDir() + File.separator + "sxs" + File.separator;
    File f = new File(pth + "list.properties");
    if (!f.exists()) {
        new File(pth).mkdir();
        FileWriter fw = new FileWriter(f);
        fw.write("1=q=tasmanian%20devil&gridsize=0.01&layers=aus1\n"
                + "2=q=tasmanian%20devil&gridsize=0.1&layers=aus1\n"
                + "3=q=tasmanian%20devil&gridsize=10&layers=aus1");
        fw.flush();//from   ww  w.  ja v a 2s .  c  o m
        fw.close();
    }
}

From source file:hudson.remoting.Launcher.java

/**
 * Listens on an ephemeral port, record that port number in a port file,
 * then accepts one TCP connection.//  www . j  a  va2  s. com
 */
private void runAsTcpServer() throws IOException, InterruptedException {
    // if no one connects for too long, assume something went wrong
    // and avoid hanging foreever
    ServerSocket ss = new ServerSocket(0, 1);
    ss.setSoTimeout(30 * 1000);

    // write a port file to report the port number
    FileWriter w = new FileWriter(tcpPortFile);
    w.write(String.valueOf(ss.getLocalPort()));
    w.close();

    // accept just one connection and that's it.
    // when we are done, remove the port file to avoid stale port file
    Socket s;
    try {
        s = ss.accept();
        ss.close();
    } finally {
        tcpPortFile.delete();
    }

    runOnSocket(s);
}

From source file:es.ubu.XRayDetector.datos.GestorArff.java

/**
 * Creates a new ARFF file.//w w  w .j  a va 2  s.c  o  m
 * 
 * @param numHilo The number of the thread which manages the new ARFF file.
 * @param featuresString The features extracted from the image.
 * @param header The header of the file.
 */
public void crearArff(int numHilo, String featuresString, String header) {

    File outputFile;
    FileWriter arffFile;

    outputFile = new File("./res/arff/Arff_entrenamiento" + numHilo + ".arff");
    try {
        if (!outputFile.exists()) {
            outputFile.createNewFile();
            if (numHilo == 0) {
                arffFile = new FileWriter(outputFile);
                arffFile.write(header);
            } else {
                arffFile = new FileWriter(outputFile);
            }
        } else {
            // si ya esta creado se escribe a continuacion
            arffFile = new FileWriter(outputFile, true);
        }
        arffFile.write(featuresString + "\n");
        arffFile.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.ku.brc.af.ui.forms.persist.ViewLoader.java

/**
 * Save out a viewSet to a file/*w  ww . j  a va  2  s . com*/
 * @param viewSet the viewSet to save
 * @param filename the filename (full path) as to where to save it
 */
public static void save(final ViewSet viewSet, final String filename) {
    try {
        Vector<ViewSet> viewsets = new Vector<ViewSet>();
        viewsets.add(viewSet);

        File file = new File(filename);
        FileWriter fw = new FileWriter(file);

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

        BeanWriter beanWriter = new BeanWriter(fw);
        XMLIntrospector introspector = beanWriter.getXMLIntrospector();
        introspector.getConfiguration().setWrapCollectionsInElement(false);
        beanWriter.getBindingConfiguration().setMapIDs(false);
        beanWriter.setWriteEmptyElements(false);

        beanWriter.enablePrettyPrint();
        beanWriter.write(viewSet);

        fw.close();

    } catch (Exception ex) {
        log.error("error writing views", ex);
    }
}

From source file:net.sf.reportengine.out.TestHtmlReportOutput.java

/**
 * Test method for/* w  w w .jav a 2s.c om*/
 * {@link net.sf.reportengine.out.AbstractFreemarkerReportOutput#close()}.
 */
@Test
public void testCloseWriterException() {
    try {
        FileWriter fileWriter = new FileWriter("./target/TestClosingWriterException.html");
        HtmlReportOutput classUnderTest = new HtmlReportOutput(fileWriter, true);
        classUnderTest.open();
        classUnderTest.output("emptyLine.ftl");
        classUnderTest.close();

        // at this point the writer should be already closed
        fileWriter.write("if you see this the test has failed");
        fail("An IOException should have been thrown at this point");
    } catch (IOException e) {
        assertEquals("Stream closed", e.getMessage());
    }
}

From source file:eu.freme.i18n.okapi.api.EInternationalizationAPITest.java

public void testRoundTripping(String originalFilePath, String enrichmentPath)
        throws ConversionException, IOException {
    // STEP 1: creation of the skeleton file: the TTL file with the context
    // including markups.
    InputStream originalFile = getClass().getResourceAsStream(originalFilePath);
    Reader skeletonReader = eInternationalizationAPI.convertToTurtleWithMarkups(originalFile,
            EInternationalizationAPI.MIME_TYPE_HTML);

    // STEP 2: save the skeleton file somewhere on the machine
    BufferedReader br = new BufferedReader(skeletonReader);
    File skeletonFile = File.createTempFile("freme-i18n-unittest", "");
    FileWriter writer = new FileWriter(skeletonFile);
    String line;/* w  ww . j  av  a 2s. co  m*/
    while ((line = br.readLine()) != null) {
        // System.out.println(line);
        writer.write(line);
    }
    br.close();
    writer.close();

    // STEP 3: execute the conversion back by submitting the skeleton file
    // and the enriched file
    InputStream skeletonStream = new FileInputStream(skeletonFile);
    InputStream turtle = getClass().getResourceAsStream(enrichmentPath);
    Reader reader = eInternationalizationAPI.convertBack(skeletonStream, turtle);
    br = new BufferedReader(reader);
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    br.close();
    skeletonFile.delete();
}

From source file:dumptspacket.Main.java

public void start(String[] args) throws org.apache.commons.cli.ParseException {
    final String fileName;
    final Long limit;
    final Set<Integer> pids;

    System.out.println("args   : " + dumpArgs(args));

    final Option fileNameOption = Option.builder("f").required().longOpt("filename").desc("ts??")
            .hasArg().type(String.class).build();

    final Option limitOption = Option.builder("l").required(false).longOpt("limit")
            .desc("??(???????EOF??)").hasArg()
            .type(Long.class).build();

    final Option pidsOption = Option.builder("p").required().longOpt("pids")
            .desc("pid(?16?)").type(String.class).hasArgs().build();

    Options opts = new Options();
    opts.addOption(fileNameOption);//from   w w w  .j a  v a2  s  .c o  m
    opts.addOption(limitOption);
    opts.addOption(pidsOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();

    try {

        // parse options
        cl = parser.parse(opts, args);

        // handle interface option.
        fileName = cl.getOptionValue(fileNameOption.getOpt());
        if (fileName == null) {
            throw new ParseException("????????");
        }

        // handlet destination option.
        Long xl = null;
        try {
            xl = Long.parseUnsignedLong(cl.getOptionValue(limitOption.getOpt()));
        } catch (NumberFormatException e) {
            xl = null;
        } finally {
            limit = xl;
        }

        Set<Integer> x = new HashSet<>();
        List<String> ls = new ArrayList<>();
        ls.addAll(Arrays.asList(cl.getOptionValues(pidsOption.getOpt())));
        for (String s : ls) {
            try {
                x.add(Integer.parseUnsignedInt(s, 16));
            } catch (NumberFormatException e) {
                throw new ParseException(e.getMessage());
            }
        }
        pids = Collections.unmodifiableSet(x);

        System.out.println("Starting application...");
        System.out.println("filename   : " + fileName);
        System.out.println("limit : " + limit);
        System.out.println("pids : " + dumpSet(pids));

        // your code
        TsReader reader;
        if (limit == null) {
            reader = new TsReader(new File(fileName), pids);
        } else {
            reader = new TsReader(new File(fileName), pids, limit);
        }

        Map<Integer, List<TsPacketParcel>> ret = reader.getPackets();
        try {
            for (Integer pid : ret.keySet()) {

                FileWriter writer = new FileWriter(fileName + "_" + Integer.toHexString(pid) + ".txt");

                for (TsPacketParcel par : ret.get(pid)) {
                    String text = Hex.encodeHexString(par.getPacket().getData());
                    writer.write(text + "\n");

                }
                writer.flush();
                writer.close();
            }
        } catch (IOException ex) {
            LOG.fatal("", ex);
        }

    } catch (ParseException e) {
        // print usage.
        help.printHelp("My Java Application", opts);
        throw e;
    } catch (FileNotFoundException ex) {
        LOG.fatal("", ex);
    }
}

From source file:com.swdouglass.winter.Winter.java

public void generateClassFromTable(String inTableName, String inIdColumnName, String inPackageName) {
    String outputDir = System.getProperty("winter.output_dir", System.getProperty("user.dir"));

    // convert java package name to directory path
    StringBuilder sb = new StringBuilder(outputDir);
    sb.append(FS);/* ww w  . j  a va 2  s  . c  om*/
    String[] parts = inPackageName.split("\\.");
    for (int i = 0; i < parts.length; i++) {
        sb.append(parts[i]);
        sb.append(FS);
    }
    File packageDir = new File(sb.toString());
    packageDir.mkdirs();
    String className = dbNameToJavaName(inTableName, JAVA_CLASS);
    sb.append(className);
    StringBuilder hbm = new StringBuilder(sb.toString());
    sb.append(".java");

    File classFile = new File(sb.toString());
    hbm.append(".hbm.xml");
    File hbmFile = new File(hbm.toString());
    try {
        FileWriter fw = new FileWriter(classFile);
        fw.write(readFileAsString(System.getProperty("winter.license", "license.txt"), JAVA_COMMENT));
        fw.write(javaFromTable(inPackageName, className, inTableName, inIdColumnName));
        fw.flush();
        fw.close();
        fw = new FileWriter(hbmFile);
        //fw.write(readFileAsString(System.getProperty("winter.license", "license.txt"), XML_COMMENT));
        fw.write(hbmFromTable(inPackageName, className, inTableName, inIdColumnName));
        fw.flush();
        fw.close();
    } catch (IOException ex) {
        logger.severe(ex.toString());
    }
}

From source file:com.athena.chameleon.engine.core.analyzer.AbstractAnalyzer.java

/**
 * <pre>//from   w ww . j  a va2s .c o  m
 * jboss-classloading.xml ?? ?.
 * </pre>
 * @param parentPath
 * @param domain
 * @param patentDomain
 */
protected void makeClassLoading(File parentPath, String domain, String patentDomain) {
    if (parentPath != null && domain != null) {
        StringBuilder sb = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");

        if (StringUtils.isEmpty(patentDomain)) {
            sb.append("<classloading xmlns=\"urn:jboss:classloading:1.0\"\r\n").append("        domain=\"")
                    .append(domain).append("\"\r\n").append("        export-all=\"NON_EMPTY\"\r\n")
                    .append("        import-all=\"true\"\r\n").append("        parent-first=\"false\">\r\n")
                    .append("</classloading>");
        } else {
            /*
            sb.append("<classloading xmlns=\"urn:jboss:classloading:1.0\"\r\n")
               .append("        domain=\"").append(domain).append("\"\r\n")
               .append("        parent-domain=\"").append(patentDomain).append("\"\r\n")
               .append("        export-all=\"NON_EMPTY\"\r\n")
               .append("        import-all=\"true\">\r\n")
               .append("</classloading>");
            */
            sb.append("<classloading xmlns=\"urn:jboss:classloading:1.0\"\r\n").append("        name=\"")
                    .append(domain).append("\"\r\n").append("        domain=\"DefaultDomain\"\r\n")
                    .append("        parent-domain=\"Ignored\"\r\n")
                    .append("        parent-first=\"false\"\r\n").append("        export-all=\"NON_EMPTY\"\r\n")
                    .append("        import-all=\"true\">\r\n").append("</classloading>");
        }

        try {
            File file = new File(parentPath, "jboss-classloading.xml");
            FileWriter fw = new FileWriter(file);
            fw.write(sb.toString());
            IOUtils.closeQuietly(fw);
        } catch (IOException e) {
            logger.error("IOException has occurred.", e);
        }
    }
}