Example usage for java.io PrintWriter PrintWriter

List of usage examples for java.io PrintWriter PrintWriter

Introduction

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

Prototype

public PrintWriter(File file) throws FileNotFoundException 

Source Link

Document

Creates a new PrintWriter, without automatic line flushing, with the specified file.

Usage

From source file:Json.Type.java

public Type(String type) {
    JSONObject obj = new JSONObject();
    obj.put("type", type);
    File file = new File("type");

    try {/* w w w .  j  a va 2 s .c  o  m*/
        //?,  ?   ??  ? 
        if (!file.exists()) {
            file.createNewFile();
        }

        //PrintWriter ? ? ?  
        PrintWriter out = new PrintWriter(file.getAbsoluteFile());

        try {
            //? ?  
            out.print(obj);
        } finally {
            //?     
            //   ??
            out.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.rsmart.rfabric.logging.FormattedLogger.java

/**
 * Applies a pattern with parameters to create a {@link String} used as a logging message
 *  /*from w ww . jav a2s.c  o  m*/
 * 
 * @param pattern to format against
 * @param objs an array of objects used as parameters to the <code>pattern</code>
 * @return Logging Message
 */
private static final String getMessage(String pattern, Object... objs) {
    StringWriter retval = new StringWriter();
    PrintWriter writer = new PrintWriter(retval);

    writer.printf(pattern, objs);

    return retval.toString();
}

From source file:ir.pooyahfp.matrixcli.ProgramTest.java

@Test
public void testSetWriter() throws Exception {
    program.setWriter(new PrintWriter(System.err));
    program.runCommand("matrix y 3 3");
    program.runCommand("show y");
}

From source file:com.jaeksoft.searchlib.util.ExceptionUtils.java

public final static String getFullStackTrace(StackTraceElement[] stackTrace) {
    StringWriter sw = null;/*from  w  w  w .jav  a  2 s  .  co  m*/
    PrintWriter pw = null;
    try {
        sw = new StringWriter();
        pw = new PrintWriter(sw);
        for (StackTraceElement element : stackTrace)
            pw.println(element);
        return sw.toString();
    } finally {
        IOUtils.close(pw, sw);
    }
}

From source file:mx.unam.ecologia.gye.coalescence.app.EvaluateAncestry.java

protected static final void process(CompoundSequence mrca, List leaves) {
    try {/*from  w  w w  . j a  va 2  s  .c o  m*/

        PrintWriter pw = new PrintWriter(System.out);
        HaplotypeFreqSet len1 = new HaplotypeFreqSet(new CompoundSequenceLengthComparator());
        HaplotypeFreqSet len2 = new HaplotypeFreqSet(new CompoundSequenceLengthComparator());
        HaplotypeFreqSet ident = new HaplotypeFreqSet(new CompoundSequenceIdentityComparator());

        for (int i = 0; i < leaves.size(); i++) {
            UniParentalGene upgene = (UniParentalGene) leaves.get(i);
            CompoundSequence h = upgene.getCompoundSequence();
            len1.add(h);
            ident.add(h);
            CompoundSequence cs = h.getCopy();
            cs.setLocus(true);
            len2.add(cs);
        }

        //Identity
        pw.println("IDENTITY");
        ident.sort(new CSAncestryComparator());
        CompoundSequence cs = ident.get(0);
        pw.println("MA: " + ident.contains(cs));
        pw.println("MF: " + (ident.findMostFrequent() + 1));
        pw.println(ident.toFullString());

        pw.println();
        pw.println();
        pw.println("MULTILOCUS");
        pw.println("MA: " + len1.contains(cs));
        pw.println("MF: " + (len1.findMostFrequent() + 1));
        pw.println(len1.toResumeString());

        pw.println();
        pw.println();
        pw.println("LOCUS");
        cs.setLocus(true);
        pw.println("MA: " + len2.contains(cs));
        pw.println("MF: " + (len2.findMostFrequent() + 1));
        pw.println(len2.toResumeString());
        pw.flush();

        SparseGraph sg = new SparseGraph();

        List<CompoundSequence> ht = len1.getHaplotypes();
        //add vertices
        List<SparseVertex> vertices = new ArrayList<SparseVertex>(ht.size());

        for (Iterator<CompoundSequence> iter = ht.iterator(); iter.hasNext();) {
            CompoundSequence cseq = iter.next();
            SparseVertex sv = new SparseVertex();
            sv.addUserDatum("seq", cseq, UserData.SHARED);
            sv.addUserDatum("freq", len1.getFrequency(cseq), UserData.SHARED);
            if (cseq.equals(cs)) {
                sv.addUserDatum("mf", true, UserData.SHARED);
            }
            sg.addVertex(sv);
            vertices.add(sv);
        }
        //add edges
        for (int i = 0; i < ht.size(); i++) {
            for (int j = 0; j <= i; j++) {
                double d = DistanceCalculator.calculateMultilocusLengthDistance(ht.get(i), ht.get(j));
                UndirectedSparseEdge ue = new UndirectedSparseEdge(vertices.get(i), vertices.get(j));
                ue.setUserDatum(EDGE_WEIGHT_KEY, new Double(d), UserData.SHARED);
                if (d != 0) {
                    sg.addEdge(ue);
                }
            }
        }

        //System.out.println(sg.toString());
        //System.out.println(GraphMatrixOperations.graphToSparseMatrix(sg,EDGE_WEIGHT_KEY));
        visualizeGraph(sg);

        //Prim
        SparseGraph nsg = new SparseGraph();
        FibonacciHeap<Vertex, Double> q = new FibonacciHeap<Vertex, Double>();
        Map<Vertex, Vertex> pi = new HashMap<Vertex, Vertex>((int) (ht.size() * 1.3));
        //System.out.println("Have structures");
        Vertex r = null;
        for (SparseVertex u : vertices) {
            q.add(u, Double.MAX_VALUE);
            u.copy(nsg);
            if (r == null) {
                r = u;
            } else {
                //start from max freq
                r = (((Integer) r.getUserDatum("freq")).compareTo((Integer) u.getUserDatum("freq")) > 0) ? r
                        : u;
            }
        }
        q.decreaseKey(r, 0d);
        //System.out.println("initialized starting loop");
        do {
            Vertex u = (Vertex) q.popMin();
            Set<Vertex> s = u.getNeighbors();
            for (Vertex v : s) {
                Edge e = u.findEdge(v);
                double w = (Double) e.getUserDatum(EDGE_WEIGHT_KEY);
                if (q.contains(v) && w < q.getPriority(v)) {
                    pi.put(v, u);
                    q.decreaseKey(v, w);
                }
            }
        } while (q.size() > 0);

        //put edges

        for (Map.Entry<Vertex, Vertex> entry : pi.entrySet()) {
            Vertex v = entry.getKey();
            Vertex u = entry.getValue();
            u.findEdge(v).copy(nsg);
        }

        /*
        for(SparseVertex sv:vertices) {
          //edges
          Set s =  sv.getIncidentEdges();
          Edge[] edges = (Edge[])s.toArray(new Edge[s.size()]);
          //sort
          Arrays.sort(edges,new Comparator<Edge>() {
            public int compare(Edge o1, Edge o2) {
              return ((Double)o2.getUserDatum(EDGE_WEIGHT_KEY)).compareTo((Double)o1.getUserDatum(EDGE_WEIGHT_KEY));
            }
          });
          System.out.println(Arrays.toString(edges));
          //just leave the edge with the lowest weight
          for(Edge e:edges) {
            if(sv.degree() > 1 && e.getOpposite(sv).degree() > 1) {
              sg.removeEdge(e);
              System.out.println("Removing " + e.toString() + "::w="+e.getUserDatum(EDGE_WEIGHT_KEY));
            }
          }
                
          System.out.println(sv.toString());
        }
         */
        visualizeGraph(nsg);
    } catch (Exception ex) {
        log.error("process()", ex);
    }

}

From source file:StringUtil.java

/**
 * Get the stack trace of the supplied exception.
 * /*from w  w w .  j a  v a2s  .c o  m*/
 * @param throwable the exception for which the stack trace is to be returned
 * @return the stack trace, or null if the supplied exception is null
 */
public static String getStackTrace(Throwable throwable) {
    if (throwable == null)
        return null;
    final ByteArrayOutputStream bas = new ByteArrayOutputStream();
    final PrintWriter pw = new PrintWriter(bas);
    throwable.printStackTrace(pw);
    pw.close();
    return bas.toString();
}

From source file:com.jredrain.base.utils.CommandUtils.java

public static File createShellFile(String command, String shellFileName) {
    String dirPath = IOUtils.getTempFolderPath();
    File dir = new File(dirPath);
    if (!dir.exists())
        dir.mkdirs();/*from  w  w w  .j a va2 s. c  om*/

    String tempShellFilePath = dirPath + File.separator + shellFileName + ".sh";
    File shellFile = new File(tempShellFilePath);
    try {
        if (!shellFile.exists()) {
            PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(tempShellFilePath)));
            out.write("#!/bin/bash\n" + command);
            out.flush();
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        return shellFile;
    }
}

From source file:edu.umn.msi.tropix.common.logging.ExceptionUtils.java

public static String toString(@Nullable final Throwable throwable) {
    if (throwable == null) {
        return null;
    }/*from w ww  . j  a v  a2s.  c o  m*/
    final StringWriter stackWriter = new StringWriter();
    throwable.printStackTrace(new PrintWriter(stackWriter));
    return stackWriter.toString();
}

From source file:net.panthema.BispanningGame.GraphString.java

public static String write_graph(MyGraph g, Transformer<Integer, Point2D> gl) {
    ByteArrayOutputStream ba = new ByteArrayOutputStream();
    PrintWriter pw = new PrintWriter(ba);

    // print the vertex list

    pw.print('V');
    pw.print(g.getVertexCount());//  w  w  w.jav a 2s  . c  o m
    pw.print(':');

    Collection<Integer> vcoll = g.getVertices();
    ArrayList<Integer> vlist = new ArrayList<Integer>(vcoll);
    Collections.sort(vlist, new Comparator<Integer>() {
        public int compare(Integer arg0, Integer arg1) {
            return arg0 - arg1;
        }
    });

    for (Integer v : vlist) {
        pw.print('i');
        pw.print(v);

        Point2D pos = gl.transform(v);
        pw.print('x');
        pw.print((int) pos.getX());
        pw.print('y');
        pw.print((int) pos.getY());

        pw.print('/');
    }
    pw.print(';');

    // print the edge list

    pw.print('E');
    pw.print(g.getEdgeCount());
    pw.print(':');

    Collection<MyEdge> ecoll = g.getEdges();
    ArrayList<MyEdge> elist = new ArrayList<MyEdge>(ecoll);
    Collections.sort(elist, new Comparator<MyEdge>() {
        public int compare(MyEdge arg0, MyEdge arg1) {
            return arg0.id - arg1.id;
        }
    });

    for (MyEdge e : elist) {
        Integer e_x = g.getEndpoints(e).getFirst();
        Integer e_y = g.getEndpoints(e).getSecond();

        pw.print('i');
        pw.print(e.id);

        pw.print('t');
        pw.print(e_x);
        pw.print('h');
        pw.print(e_y);

        pw.print('c');
        pw.print(e.color);

        pw.print('/');
    }
    pw.print(';');

    pw.flush();

    return ba.toString();
}

From source file:Main.java

private static Connection getHSQLConnection() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    String url = "jdbc:hsqldb:mem:data/tutorial";

    DriverManager.setLogWriter(new PrintWriter("yourFileName.log"));

    return DriverManager.getConnection(url, "sa", "");
}