Example usage for java.io PrintWriter println

List of usage examples for java.io PrintWriter println

Introduction

In this page you can find the example usage for java.io PrintWriter println.

Prototype

public void println(Object x) 

Source Link

Document

Prints an Object and then terminates the line.

Usage

From source file:isl.FIMS.utils.Utils.java

private static long getFreeSpaceOnWindows(String path) throws Exception {
    long bytesFree = -1;

    File script = new File(System.getProperty("java.io.tmpdir"), //$NON-NLS-1$
            "script.bat"); //$NON-NLS-1$
    PrintWriter writer = new PrintWriter(new FileWriter(script, false));
    writer.println("dir \"" + path + "\""); //$NON-NLS-1$ //$NON-NLS-2$
    writer.close();//from   ww w  .j  a va2  s .c  o m

    // get the output from running the .bat file
    Process p = Runtime.getRuntime().exec(script.getAbsolutePath());
    InputStream reader = new BufferedInputStream(p.getInputStream());
    StringBuffer buffer = new StringBuffer();
    for (;;) {
        int c = reader.read();
        if (c == -1) {
            break;
        }
        buffer.append((char) c);
    }
    String outputText = buffer.toString();
    reader.close();

    StringTokenizer tokenizer = new StringTokenizer(outputText, "\n"); //$NON-NLS-1$
    String line = null;
    while (tokenizer.hasMoreTokens()) {
        line = tokenizer.nextToken().trim();
        // see if line contains the bytes free information

    }
    tokenizer = new StringTokenizer(line, " "); //$NON-NLS-1$
    tokenizer.nextToken();
    tokenizer.nextToken();
    bytesFree = Long.parseLong(tokenizer.nextToken().replace('.', ',').replaceAll(",", "")); //$NON-NLS-1$//$NON-NLS-2$
    return bytesFree;
}

From source file:com.hp.test.framework.Utlis.java

public static void create_tempfile(File SourceFile, File TempFile, String passed_count, String failed_count,
        String skipped_count, String graphType) {
    try {/*  w w w .j a v a 2  s .  c  o m*/
        InputStream ips = new FileInputStream(SourceFile);
        InputStreamReader ipsr = new InputStreamReader(ips);
        BufferedReader br = new BufferedReader(ipsr);

        FileWriter fw = new FileWriter(TempFile);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter fileOut = new PrintWriter(bw);
        //        fileOut.println (string+"\n test of read and write !!"); 
        //  fileOut.close();

        String line;
        String variable = "s";
        if (graphType.equals("line")) {
            variable = "line";

        }
        //ArrayList<String> ar = new ArrayList<String>();
        int i = 0;
        while ((line = br.readLine()) != null) {

            if (i == 0) {
                fileOut.println(line);
                i = i + 1;
                continue;

            }
            if (line.contains("var " + variable)) {
                i = i + 1;
                log.info(line);
                String tem_ar[] = line.split("=");
                log.info(tem_ar[1]);
                String variable1 = "var " + variable + "1 = [" + passed_count + "];";
                String variable2 = "var " + variable + "2 = [" + failed_count + "];";
                String variable3 = "var " + variable + "3 = [" + skipped_count + "];";
                if (i == 2) {
                    fileOut.println(variable1);
                    fileOut.println(variable2);
                    fileOut.println(variable3);
                }
                // string += line + "\n";
                // Run_counts.put(runs.get(count).toString(), ar);

            } else {
                fileOut.println(line);
            }
        }

        fileOut.close();
        br.close();
        log.info("Temp file after replacing counts created successfully--> " + TempFile.getPath());
    } catch (Exception e) {
        System.out.println(e.toString());

    }
}

From source file:delphsim.model.Resultado.java

/**
 * Mtodo esttico que exporta los valores obtenidos tras la simulacin al
 * formato textual CSV./*from  w  ww.  j  a v a 2 s. c o  m*/
 * @param destino El archivo de destino.
 * @param cabecera La cabecera del archivo CSV (primera fila del documento).
 * @param temps Array con los archivos temporales de los cuales obtener los
 *              datos a exportar.
 * @param numPuntosTotal El nmero de puntos total que contienen los
 *                       archivos temporales.
 * @param numPuntosExportar El nmero de puntos que quiere obtener el usuario.
 * @throws java.io.IOException Si hubiera algn problema al crear el archivo en disco.
 */
public static void exportarComoCSV(File destino, String cabecera, File[] temps, long numPuntosTotal,
        long numPuntosExportar) throws IOException {
    // Creamos el archivo de salida y escribimos la cabecera en l
    PrintWriter salida = new PrintWriter(new BufferedWriter(new FileWriter(destino)));
    salida.println(cabecera);
    // Creamos los bfers de lectura para leer los temporales
    BufferedReader[] buffers = new BufferedReader[temps.length];
    for (int i = 0; i < temps.length; i++) {
        buffers[i] = new BufferedReader(new FileReader(temps[i]));
    }
    // Calculamos cada cuanto tenemos que guardar un punto
    double cadaCuanto;
    if (numPuntosTotal == numPuntosExportar) {
        cadaCuanto = 1.0d;
    } else {
        cadaCuanto = new Double(numPuntosTotal) / new Double(numPuntosExportar - 1);
    }
    long siguientePuntoExportar = 0;
    long contadorNumPuntoLeido = 0;
    long contadorNumPuntosExportados = 0;
    // Comenzamos a leer los temporales escribiendo en el CSV de salida
    String nuevaLinea = "";
    String leido = null;
    for (int i = 0; i < buffers.length; i++) {
        leido = buffers[i].readLine();
        nuevaLinea += leido + ",";
    }
    // En el momento en que se lee un null, se termina
    while (leido != null) {
        nuevaLinea = nuevaLinea.substring(0, nuevaLinea.length() - 1);
        if (siguientePuntoExportar == contadorNumPuntoLeido) {
            salida.println(nuevaLinea);
            contadorNumPuntosExportados++;
            siguientePuntoExportar = Math.round(cadaCuanto * contadorNumPuntosExportados);
            if (siguientePuntoExportar >= numPuntosTotal) {
                siguientePuntoExportar = numPuntosTotal - 1;
            }
        }
        nuevaLinea = "";
        for (int i = 0; i < buffers.length; i++) {
            leido = buffers[i].readLine();
            nuevaLinea += leido + ",";
        }
        contadorNumPuntoLeido++;
    }
    // Cerramos los bfers y el archivo de salida
    for (int i = 0; i < buffers.length; i++) {
        buffers[i].close();
    }
    salida.flush();
    salida.close();
}

From source file:com.oculusinfo.ml.spark.unsupervised.TestDPMeans.java

public static void genTestData(int k) {
    PrintWriter writer;
    try {/* www .j  av  a2 s  . c o m*/
        writer = new PrintWriter("test.txt", "UTF-8");

        // each class size is equal 
        int classSize = 1000000 / k;

        double stdDev = 30.0;

        // generate k classes of data points using a normal distribution with random means and fixed std deviation
        for (int i = 0; i < k; i++) {
            Random rnd = new Random();

            double meanLat = rnd.nextDouble() * 400.0;
            double meanLon = rnd.nextDouble() * 400.0;

            // randomly generate a dataset of lat, lon points
            for (int j = 0; j < classSize; j++) {
                double x = rnd.nextGaussian() * stdDev + meanLat;
                double y = rnd.nextGaussian() * stdDev + meanLon;

                writer.println(x + "," + y);
            }
        }
        writer.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:gov.nih.nci.caarray.application.translation.geosoft.GeoSoftFileWriterUtil.java

@SuppressWarnings("PMD.ExcessiveMethodLength")
private static void writeSampleSection(Hybridization h, PrintWriter out) {
    final Set<Source> sources = new TreeSet<Source>(ENTITY_COMPARATOR);
    final Set<Sample> samples = new TreeSet<Sample>(ENTITY_COMPARATOR);
    final Set<Extract> extracts = new TreeSet<Extract>(ENTITY_COMPARATOR);
    final Set<LabeledExtract> labeledExtracts = new TreeSet<LabeledExtract>(ENTITY_COMPARATOR);
    GeoSoftFileWriterUtil.collectBioMaterials(h, sources, samples, extracts, labeledExtracts);

    out.print("^SAMPLE=");
    out.println(h.getName());
    out.print("!Sample_title=");
    out.println(h.getName());/*from   www  .jav a2  s.co  m*/
    writeDescription(out, h, samples);
    writeData(h, out);
    writeSources(out, sources);
    writeOrganism(sources, samples, h.getExperiment(), out);
    final Set<ProtocolApplication> pas = new TreeSet<ProtocolApplication>(ENTITY_COMPARATOR);
    pas.addAll(h.getProtocolApplications());
    collectAllProtocols(labeledExtracts, pas);
    collectAllProtocols(extracts, pas);
    collectAllProtocols(samples, pas);
    collectAllProtocols(sources, pas);

    writeProtocol(pas, "Sample_treatment_protocol", PREDICATE_TREATMENT, out);
    writeProtocol(pas, "Sample_growth_protocol", PREDICATE_GROWTH, out);
    writeProtocol(pas, "Sample_extract_protocol", PREDICATE_EXTRACT, out);
    writeProtocol(getAllProtocols(extracts), "Sample_label_protocol", PREDICATE_LABELING, out);
    writeProtocol(getAllProtocols(labeledExtracts), "Sample_hyb_protocol", PREDICATE_HYB, out);
    writeProtocol(h.getProtocolApplications(), "Sample_scan_protocol", PREDICATE_SCAN, out);
    writeProtocolsForData(h.getRawDataCollection(), "Sample_data_processing", out);

    for (final LabeledExtract labeledExtract : labeledExtracts) {
        out.print("!Sample_label=");
        out.println(labeledExtract.getLabel().getValue());
    }
    writeProviders(sources, out);

    out.print("!Sample_platform_id=");
    out.println(h.getArray().getDesign().getGeoAccession());

    final Set<String> uniqueEntries = new HashSet<String>();
    for (final AbstractFactorValue fv : h.getFactorValues()) {
        writeCharacteristics(fv.getFactor().getName(), fv.getDisplayValue(), out, uniqueEntries);
    }
    writeCharacteristics(labeledExtracts, out, uniqueEntries);
    writeCharacteristics(extracts, out, uniqueEntries);
    writeCharacteristics(samples, out, uniqueEntries);
    writeCharacteristics(sources, out, uniqueEntries);

    writeMaterialTypes(extracts, labeledExtracts, out);
}

From source file:edu.ku.brc.specify.extras.ViewToSchemaReview.java

/**
 * /*from www  .j  a v a  2  s.  co  m*/
 */
public static void dumpFormFieldList(final boolean doShowInBrowser) {
    List<ViewIFace> viewList = ((SpecifyAppContextMgr) AppContextMgr.getInstance()).getEntirelyAllViews();
    Hashtable<String, ViewIFace> hash = new Hashtable<String, ViewIFace>();

    for (ViewIFace view : viewList) {
        hash.put(view.getName(), view);
    }
    Vector<String> names = new Vector<String>(hash.keySet());
    Collections.sort(names);

    try {
        File file = new File("FormFields.html");
        PrintWriter pw = new PrintWriter(file);

        pw.println(
                "<HTML><HEAD><TITLE>Form Fields</TITLE><link rel=\"stylesheet\" href=\"http://specify6.specifysoftware.org/schema/specify6.css\" type=\"text/css\"/></HEAD><BODY>");
        pw.println("<center>");
        pw.println("<H2>Forms and Fields</H2>");
        pw.println("<center><table class=\"brdr\" border=\"0\" cellspacing=\"0\">");

        int formCnt = 0;
        int fieldCnt = 0;
        for (String name : names) {
            ViewIFace view = hash.get(name);
            boolean hasEdit = false;
            for (AltViewIFace altView : view.getAltViews()) {
                if (altView.getMode() != AltViewIFace.CreationMode.EDIT) {
                    hasEdit = true;
                    break;
                }
            }

            //int numViews = view.getAltViews().size();
            for (AltViewIFace altView : view.getAltViews()) {
                //AltView av = (AltView)altView;
                if ((hasEdit && altView.getMode() == AltViewIFace.CreationMode.VIEW)) {
                    ViewDefIFace vd = altView.getViewDef();
                    if (vd instanceof FormViewDef) {
                        formCnt++;
                        FormViewDef fvd = (FormViewDef) vd;
                        pw.println("<tr><td class=\"brdrodd\">");
                        pw.println(fvd.getName());
                        pw.println("</td></tr>");
                        int r = 1;
                        for (FormRowIFace fri : fvd.getRows()) {
                            FormRow fr = (FormRow) fri;
                            for (FormCellIFace cell : fr.getCells()) {
                                if (StringUtils.isNotEmpty(cell.getName())) {
                                    if (cell.getType() == FormCellIFace.CellType.panel) {
                                        FormCellPanelIFace panelCell = (FormCellPanelIFace) cell;
                                        for (String fieldName : panelCell.getFieldNames()) {
                                            pw.print("<tr><td ");
                                            pw.print("class=\"");
                                            pw.print(r % 2 == 0 ? "brdrodd" : "brdreven");
                                            pw.print("\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + fieldName);
                                            pw.println("</td></tr>");
                                            fieldCnt++;
                                        }

                                    } else if (cell.getType() == FormCellIFace.CellType.field
                                            || cell.getType() == FormCellIFace.CellType.subview) {
                                        pw.print("<tr><td ");
                                        pw.print("class=\"");
                                        pw.print(r % 2 == 0 ? "brdrodd" : "brdreven");
                                        pw.print("\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + cell.getName());
                                        pw.println("</td></tr>");
                                        fieldCnt++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        pw.println("</table></center><br>");
        pw.println("Number of Forms: " + formCnt + "<br>");
        pw.println("Number of Fields: " + fieldCnt + "<br>");
        pw.println("</body></html>");
        pw.close();

        try {
            if (doShowInBrowser) {
                AttachmentUtils.openURI(file.toURI());
            } else {
                JOptionPane.showMessageDialog(getTopWindow(),
                        String.format(getResourceString("FormDisplayer.OUTPUT"), file.getCanonicalFile()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.sshtools.appframework.ui.SshToolsApplication.java

public static void saveMRU(SshToolsApplication app) {
    File a = app.getApplicationPreferencesDirectory();
    if (a != null) {
        try {/*w  w w . j  a  v a 2s .c  om*/
            File f = new File(app.getApplicationPreferencesDirectory(), app.getApplicationName() + ".mru");
            PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8"), true);
            try {
                w.println(mruModel.getMRUList().toString());
            } finally {
                w.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:bizlogic.Command.java

public static int Process(String _command, Connection con, PrintWriter out) throws SQLException {

    try {//from  www  . jav  a  2s .  c  o m
        System.out.print("Processing command: ");
        System.out.println(_command);

        String string = _command;
        String[] _array = string.split(",");

        String command = _array[0];

        switch (command) {
        case "addSensor":
            bizlogic.Sensors.add(con, _array[1], _array[2], _array[3], _array[4], _array[5], _array[6]);
            bizlogic.Sensors.list(con);
            break;

        case "delSensor":
            bizlogic.Sensors.del(con, _array[1]);
            bizlogic.Sensors.list(con);
            break;

        case "listSensors":
            bizlogic.Sensors.list(con);
            out.println("sensors.json ok");
            break;

        case "addRecord":
            bizlogic.Records.add(con, _array[1], _array[2], _array[3], _array[4]);
            bizlogic.Records.list(con);
            break;

        case "delRecord":
            bizlogic.Records.del(con, _array[1]);
            bizlogic.Records.list(con);
            break;

        case "startRecords":
            bizlogic.Records.setColumn(con, _array[1], "USERCONF.LOG_LIST", "RUNNING", "true");
            // (conDB, records, column, value)
            //bizlogic.Records.list(con);
            out.println("startRecords " + _array[1]);
            break;

        case "stopRecords":
            bizlogic.Records.setColumn(con, _array[1], "USERCONF.LOG_LIST", "RUNNING", "false");
            // (conDB, records, column, value)
            //bizlogic.Records.list(con);
            out.println("stopRecords " + _array[1]);
            break;

        case "listRecords":
            bizlogic.Records.list(con);
            out.println("listRecords ok");
            break;

        case "writeCSV":
            bizlogic.Records.writeCSV(con, _array[1]);
            out.println("writeCSV " + _array[1] + " Value" + " Time");
            break;

        case "setConf":
            String[] confString = new String[] { "date", "+%D", "--set", _array[3] + " " + _array[2] };
            System.out.println("confString=" + Arrays.toString(confString));
            Process p = java.lang.Runtime.getRuntime().exec(confString);
            int setConf_status = p.waitFor();
            System.out.println("confStatus = " + Integer.toString(setConf_status));
            if (setConf_status != -1) {
                out.println("setConf " + "ok");
            } else {
                out.println("ERROR Date not set");
            }
            break;

        case "serverTime":
            DateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
            Date date = new Date(System.currentTimeMillis());
            out.println("Server time: " + sdf.format(date));
            break;

        case "changeIP":

            if (bizlogic.modSettings.validateIP(_array[1])) {
                System.out.println("changeIP to " + _array[1]);
                bizlogic.modSettings.resetIP();
                if (!_array[1].equals("0.0.0.0")) {
                    bizlogic.modSettings.setIP(_array[1]);
                }
                out.println("Server rebooting to set the IP");
                out.close();
                con.close();
                java.lang.Runtime.getRuntime().exec("sudo reboot");
            } else {
                out.println("ERROR: Bad IP address." + " Enter a valid IPv4 addess");
                System.out.println("Bad IP: " + _array[1]);
                java.lang.Runtime.getRuntime().exec(
                        "pid2=`ps aux | " + "grep \"[d]l_hwlogic\" | awk '{print $2}'`\n" + "kill -9 $pid2");
            }
            break;

        default:
            break;
        }
        return 1;
    } catch (IOException | ParseException | InterruptedException ex) {
        Logger.getLogger(Command.class.getName()).log(Level.WARNING, null, ex);
        return -1;
    }
}

From source file:com.oculusinfo.ml.spark.unsupervised.TestKMeans.java

public static void genTestData(int k) {
    PrintWriter writer;
    try {//from ww  w  .ja  v  a  2 s  .c om
        writer = new PrintWriter("test.txt", "UTF-8");

        // each class size is equal 
        int classSize = 1000000 / k;

        double stdDev = 30.0;

        // generate k classes of data points using a normal distribution with random means and fixed std deviation
        for (int i = 0; i < k; i++) {
            Random rnd = new Random();

            double meanX = rnd.nextDouble() * 400.0;
            double meanY = rnd.nextDouble() * 400.0;

            // randomly generate a dataset of x, y points
            for (int j = 0; j < classSize; j++) {
                double x = rnd.nextGaussian() * stdDev + meanX;
                double y = rnd.nextGaussian() * stdDev + meanY;

                writer.println(x + "," + y);
            }
        }
        writer.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:net.metanotion.sqlc.SQLC.java

public static int makeMethod(final PrintWriter writer, final SQLMethod m, final VoidWrap qe, final int level,
        final int[] gensym, final int[] braces, final boolean retValue) {
    makeMethod(writer, m, qe.e, level + 1, gensym, braces, retValue);
    while (braces[0] > 0) {
        writer.println("}");
        braces[0]--;//from   w w w . j  a v a  2  s .  c o m
    }
    return -1;
}