Example usage for java.io PrintStream PrintStream

List of usage examples for java.io PrintStream PrintStream

Introduction

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

Prototype

public PrintStream(File file) throws FileNotFoundException 

Source Link

Document

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

Usage

From source file:Main.java

public static PrintStream getErrorLoggerPrintStream() {
    try {// www.j a v  a  2s  . c  o m
        PrintStream s = new PrintStream(new FileOutputStream(new File("c:\\log.txt"), true));
        return s;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static void saveFile(final String fileName, final String str) {
    try {/*w w  w  . ja  va2s  .co m*/
        File f = new File(fileName);
        if (new File(f.getParent()).exists() == false) {
            f.getParentFile().mkdirs();
        }
        f.createNewFile();
        PrintStream p = new PrintStream(new FileOutputStream(f, false));
        p.println(str);
        p.close();

    } catch (Exception e) {
        e.printStackTrace();
        System.err.println(fileName);
    }
}

From source file:edu.oregonstate.eecs.mcplan.ml.KernelPrincipalComponentsAnalysis.java

public static void main(final String[] args) throws FileNotFoundException {
    final File root = new File("test/KernelPrincipalComponentsAnalysis");
    root.mkdirs();//from  ww  w  . ja va 2 s  .  c o  m
    final int seed = 42;
    final int N = 30;
    final RandomGenerator rng = new MersenneTwister(seed);
    final ArrayList<RealVector> data = new ArrayList<RealVector>();
    final ArrayList<RealVector> shuffled = new ArrayList<RealVector>();

    //      final double[][] covariance = new double[][] { {1.0, 0.0},
    //                                          {0.0, 1.0} };
    //      final MultivariateNormalDistribution p = new MultivariateNormalDistribution(
    //         rng, new double[] { 0.0, 0.0 }, covariance );
    //      final MultivariateNormalDistribution q = new MultivariateNormalDistribution(
    //         rng, new double[] { 10.0, 0.0 }, covariance );
    //
    //      for( int i = 0; i < N; ++i ) {
    //         data.add( new ArrayRealVector( p.sample() ) );
    //         data.add( new ArrayRealVector( q.sample() ) );
    //      }
    //      Fn.shuffle( rng, data );

    final double sigma = 0.01;
    final double[][] covariance = new double[][] { { sigma, 0.0 }, { 0.0, sigma } };
    final MultivariateNormalDistribution p = new MultivariateNormalDistribution(rng, new double[] { 0.0, 0.0 },
            covariance);

    for (final double r : new double[] { 1.0, 3.0, 5.0 }) {
        for (int i = 0; i < N; ++i) {
            final double theta = i * 2 * Math.PI / N;
            final double[] noise = p.sample();
            final RealVector v = new ArrayRealVector(
                    new double[] { r * Math.cos(theta) + noise[0], r * Math.sin(theta) + noise[1] });
            data.add(v);
            shuffled.add(v);
        }
    }
    Fn.shuffle(rng, shuffled);

    final Csv.Writer data_writer = new Csv.Writer(new PrintStream(new File(root, "data.csv")));
    for (final RealVector v : data) {
        for (int i = 0; i < v.getDimension(); ++i) {
            data_writer.cell(v.getEntry(i));
        }
        data_writer.newline();
    }
    data_writer.close();

    System.out.println("[Training]");
    final int Ncomponents = 2;
    final KernelPrincipalComponentsAnalysis<RealVector> kpca = new KernelPrincipalComponentsAnalysis<RealVector>(
            shuffled, new RadialBasisFunctionKernel(0.5), 1e-6);
    System.out.println("[Finished]");
    for (int i = 0; i < Ncomponents; ++i) {
        System.out.println(kpca.eigenvectors.get(i));
    }

    System.out.println("Transformed data:");
    final KernelPrincipalComponentsAnalysis.Transformer<RealVector> transformer = kpca
            .makeTransformer(Ncomponents);
    final Csv.Writer transformed_writer = new Csv.Writer(new PrintStream(new File(root, "transformed.csv")));
    for (final RealVector u : data) {
        final RealVector v = transformer.transform(u);
        System.out.println(v);
        for (int i = 0; i < v.getDimension(); ++i) {
            transformed_writer.cell(v.getEntry(i));
        }
        transformed_writer.newline();
    }
    transformed_writer.close();
}

From source file:MainClass.java

public static void print(Node node, OutputStream os) {
    PrintStream ps = new PrintStream(os);
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
        ps.print("<" + node.getNodeName());

        NamedNodeMap map = node.getAttributes();
        for (int i = 0; i < map.getLength(); i++) {
            ps.print(" " + map.item(i).getNodeName() + "=\"" + map.item(i).getNodeValue() + "\"");
        }// ww  w.  j  av  a  2  s. c om
        ps.println(">");
        return;
    case Node.ATTRIBUTE_NODE:
        ps.println(node.getNodeName() + "=\"" + node.getNodeValue() + "\"");
        return;
    case Node.TEXT_NODE:
        ps.println(node.getNodeValue());
        return;
    case Node.CDATA_SECTION_NODE:
        ps.println(node.getNodeValue());
        return;
    case Node.PROCESSING_INSTRUCTION_NODE:
        ps.println(node.getNodeValue());
        return;
    case Node.DOCUMENT_NODE:
    case Node.DOCUMENT_FRAGMENT_NODE:
        ps.println(node.getNodeName() + "=" + node.getNodeValue());
        return;
    }
}

From source file:Main.java

public static int saveToSdCard(String fileName, Bitmap bitmap) {
    int ret = 0;// www  .j ava2 s .  com
    PrintStream out = null;
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        return -1;
    }
    File file = new File(Environment.getExternalStorageDirectory().toString() + File.separator + fileName);
    if (!file.getParentFile().exists()) {
        file.getParentFile().mkdir();
    }
    try {
        out = new PrintStream(new FileOutputStream(file));
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        ret = -2;
    } finally {
        out.flush();
        out.close();
        if (!bitmap.isRecycled())
            bitmap.recycle();
    }

    return ret;
}

From source file:Main.java

public static void printErrorStackTrace(Exception ex) {
    File f = new File("/sdcard/Hisun/error.log");
    try {// w w w  . ja v a2s .  co  m
        if (!f.exists()) {
            f.createNewFile();
        }
        ex.printStackTrace(new PrintStream(f));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:mockit.integration.logging.LoggingIntegrationsTest.java

@BeforeClass
public static void redirectSystemOut() {
    originalErr = System.err;//w ww. ja  v a2 s .  c  o m

    OutputStream testOutput = new OutputStream() {
        @Override
        public void write(int b) {
            fail("Logger wrote output message!");
        }
    };

    System.setErr(new PrintStream(testOutput));
}

From source file:com.clustercontrol.util.StdOutErrLog.java

/**
 * ?log4j??<br/>//  w w w .java 2  s. c om
 */
public static void initialize() {
    System.setOut(new PrintStream(new LoggerStream(log)));
    System.setErr(new PrintStream(new LoggerStream(log)));
}

From source file:Main.java

public static void writeString(Context context, String content, String path) {
    try {/*from  ww w.ja v a  2  s  .c o m*/
        FileOutputStream fos = context.openFileOutput(path, Context.MODE_PRIVATE);
        PrintStream ps = new PrintStream(fos);
        ps.print(content);
        ps.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:edu.msu.cme.rdp.alignment.errorcheck.CompareErrorType.java

public static void main(String[] args) throws IOException {
    Options options = new Options();
    options.addOption("s", "stem", true, "Output stem (default <query_nucl.fasta>)");

    final SeqReader queryReader;
    final List<Sequence> refSeqList;
    final PrintStream alignOutStream;
    final CompareErrorType errorProcessor;
    Sequence seq;/*from  w ww .  jav  a2 s .  c o  m*/
    Map<String, PAObject> matchMap = new HashMap();

    try {
        CommandLine line = new PosixParser().parse(options, args);

        String stem;

        args = line.getArgs();
        if (args.length != 2 && args.length != 3) {
            throw new Exception("Unexpected number of arguments");
        }

        File refFile = new File(args[0]);
        File queryFile = new File(args[1]);

        if (line.hasOption("stem")) {
            stem = line.getOptionValue("stem");
        } else {
            stem = queryFile.getName();
        }

        File alignOutFile = new File(stem + "_alignments.txt");
        File mismatchOutFile = new File(stem + "_mismatches.txt");
        File indelOutFile = new File(stem + "_indels.txt");
        File qualOutFile = null;

        refSeqList = SequenceReader.readFully(refFile);
        if (args.length == 3) {
            queryReader = new QSeqReader(queryFile, new File(args[2]));
        } else {
            queryReader = new SequenceReader(queryFile);
        }

        seq = queryReader.readNextSequence();
        if (seq instanceof QSequence) {
            qualOutFile = new File(stem + "_qual.txt");
        }

        errorProcessor = new CompareErrorType(mismatchOutFile, indelOutFile, qualOutFile);
        alignOutStream = new PrintStream(alignOutFile);

        System.err.println("Starting CompareErrorType");
        System.err.println("*  Time:              " + new Date());
        System.err.println("*  Reference File:    " + refFile);
        System.err.println("*  Query File:        " + queryFile);
        if (args.length == 3) {
            System.err.println("*  Qual File:         " + args[2]);
        }
        System.err.println("*  Query format:      " + queryReader.getFormat());
        System.err.println("*  Alignment Output:  " + alignOutFile);
        System.err.println("*  Mismatches Output: " + mismatchOutFile);
        System.err.println("*  Alignment Output:  " + indelOutFile);
        if (qualOutFile != null) {
            System.err.println("*  Quality Output:    " + qualOutFile);
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp(
                "CompareErrorType [options] <ref_nucl> (<query_nucl> | <query_nucl.fasta> <query_nucl.qual>)",
                options);
        System.err.println("ERROR: " + e.getMessage());
        throw new RuntimeException(e);
        //System.exit(1);
        //return;
    }

    //ScoringMatrix scoringMatrix = ScoringMatrix.getDefaultNuclMatrix();
    // use a simple scoring function, match score 0, mismatch -1, gap opening -1, gap extension -1.
    ScoringMatrix scoringMatrix = new ScoringMatrix(
            ScoringMatrix.class.getResourceAsStream("/data/simple_scoringmatrix.txt"), -1, -1);

    do {
        try {
            PairwiseAlignment bestResult = null;
            Sequence bestSeq = null;
            boolean bestReversed = false;
            String querySeqStr = seq.getSeqString().toLowerCase();
            String reversedQuery = IUBUtilities.reverseComplement(querySeqStr);
            PAObject bestMatch = null;

            //checking if sequence has been seen before
            if (matchMap.containsKey(seq.getSeqString())) {
                bestMatch = matchMap.get(seq.getSeqString());
            } else {
                for (Sequence refSeq : refSeqList) {
                    String refSeqStr = refSeq.getSeqString().toLowerCase();
                    PairwiseAlignment result = PairwiseAligner.align(refSeqStr, querySeqStr, scoringMatrix,
                            AlignmentMode.global);
                    PairwiseAlignment reversedResult = PairwiseAligner.align(refSeqStr,
                            IUBUtilities.reverseComplement(querySeqStr), scoringMatrix, AlignmentMode.global);

                    PairwiseAlignment currBest = (result.getScore() > reversedResult.getScore()) ? result
                            : reversedResult;

                    if (bestResult == null || currBest.getScore() > bestResult.getScore()) {
                        bestResult = currBest;
                        bestSeq = refSeq;
                        if (currBest == reversedResult) {
                            bestReversed = true;
                        } else {
                            bestReversed = false;
                        }

                    }

                    //Since this is a new sequence, make a new PAObject to put into the map to compare against later
                    bestMatch = new PAObject(bestResult, bestReversed, bestSeq);
                    matchMap.put(seq.getSeqString(), bestMatch);
                }
            }
            int refStart = bestMatch.getPA().getStarti();
            int refEnd = bestMatch.getPA().getEndi();
            bestSeq = bestMatch.getRefSeq();
            bestReversed = bestMatch.getReversed();
            bestResult = bestMatch.getPA();

            //output information
            alignOutStream.println(">\t" + seq.getSeqName() + "\t" + bestSeq.getSeqName() + "\t"
                    + seq.getSeqString().length() + "\t" + refStart + "\t" + refEnd + "\t"
                    + bestResult.getScore() + "\t" + ((bestReversed) ? "\treversed" : ""));
            alignOutStream.println(bestResult.getAlignedSeqj() + "\n");
            alignOutStream.println(bestResult.getAlignedSeqi() + "\n");

            //seqi is reference seq, seqj is the refseq
            errorProcessor.processSequence(seq, bestResult.getAlignedSeqj(), bestSeq.getSeqName(),
                    bestResult.getAlignedSeqi(), refStart, bestReversed);

        } catch (Exception e) {
            throw new RuntimeException("Failed while processing seq " + seq.getSeqName(), e);
        }
    } while ((seq = queryReader.readNextSequence()) != null);
    queryReader.close();
    alignOutStream.close();
    errorProcessor.close();
}