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:com.googlecode.shutdownlistener.ShutdownUtility.java

public static void main(String[] args) throws Exception {
    final ShutdownConfiguration config = ShutdownConfiguration.getInstance();

    final String command;
    if (args.length > 0) {
        command = args[0];/*from  www . j  av a  2s.co  m*/
    } else {
        command = config.getStatusCommand();
    }

    System.out.println("Calling " + config.getHost() + ":" + config.getPort() + " with command: " + command);

    final InetAddress hostAddress = InetAddress.getByName(config.getHost());
    final Socket shutdownConnection = new Socket(hostAddress, config.getPort());
    try {
        shutdownConnection.setSoTimeout(5000);
        final BufferedReader reader = new BufferedReader(
                new InputStreamReader(shutdownConnection.getInputStream()));
        final PrintStream writer = new PrintStream(shutdownConnection.getOutputStream());
        try {
            writer.println(command);
            writer.flush();

            while (true) {
                final String line = reader.readLine();
                if (line == null) {
                    break;
                }

                System.out.println(line);
            }
        } finally {
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(writer);
        }
    } finally {
        try {
            shutdownConnection.close();
        } catch (IOException ioe) {
        }
    }

}

From source file:kjscompiler.Program.java

/**
 * @param args/* w  ww .jav a2s.c  o  m*/
 *            the command line arguments
 */
public static void main(String[] args) {

    ArgScanner as = new ArgScanner(args);

    if (as.checkValue(settingsArgName)) {
        settingsPath = as.getValue(settingsArgName);
    }

    if (as.checkValue(debugArgName)) {
        isDebug = true;
    }

    try {
        run();
    } catch (ParseException ex) {

        System.out.println("Parse Exception: " + ex.getMessage());

        if (isDebug) {
            ex.printStackTrace(new PrintStream(System.out));
        }

        System.exit(-1);
    } catch (IOException ex) {
        System.out.println("IO Exception: " + ex.getMessage());

        if (isDebug) {
            ex.printStackTrace(new PrintStream(System.out));
        }

        System.exit(-2);
    } catch (NullPointerException ex) {
        System.out.println("NullPointer Exception: " + ex.getMessage());

        if (isDebug) {
            ex.printStackTrace(new PrintStream(System.out));
        }

        System.exit(-3);
    } catch (Exception ex) {
        System.out.println("Exception: " + ex.getMessage());

        if (isDebug) {
            ex.printStackTrace(new PrintStream(System.out));
        }

        System.exit(-100);
    }

    System.exit(1);
}

From source file:ca.uqac.info.tag.Counter.TagCounter.java

public static void main(final String[] args) {
    // Parse command line arguments
    Options options = setupOptions();/*from w w w  .j a  v a 2s  .co  m*/
    CommandLine c_line = setupCommandLine(args, options);

    String redirectionFile = "";
    String tagAnalyse = "";
    String inputFile = "";

    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }

    //Contains a redirection file for the output
    if (c_line.hasOption("redirection")) {
        try {
            redirectionFile = c_line.getOptionValue("redirection");
            PrintStream ps;
            ps = new PrintStream(redirectionFile);
            System.setOut(ps);
        } catch (FileNotFoundException e) {
            System.out.println("Redirection error !!!");
            e.printStackTrace();
        }
    }

    //Contains a tag
    if (c_line.hasOption("Tag")) {
        tagAnalyse = c_line.getOptionValue("t");
    } else {
        System.err.println("No Tag in Arguments");
        System.exit(ERR_ARGUMENTS);
    }

    //Contains a InputFile 
    if (c_line.hasOption("InputFile")) {
        inputFile = c_line.getOptionValue("i");
    } else {
        System.err.println("No Input File in Arguments");
        System.exit(ERR_ARGUMENTS);
    }

    //Start of the program
    System.out.println("-----------------------------------------------");
    System.out.println("The count of the Tag is start !!!");

    // Throw the Sax parsing for the file 
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser;
        parser = factory.newSAXParser();

        File Tagfile = new File(inputFile);
        DefaultHandler manager = new SaxTagHandlers(tagAnalyse);
        parser.parse(Tagfile, manager);
    } catch (ParserConfigurationException e) {
        System.out.println("Parser Configuration Exception for Sax !!!");
        e.printStackTrace();

    } catch (SAXException e) {
        System.out.println("Sax Exception during the parsing !!!");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("Input/Ouput Exception during the Sax parsing !!!");
        e.printStackTrace();
    }
}

From source file:edu.msu.cme.rdp.probematch.cli.PrimerMatch.java

public static void main(String[] args) throws Exception {

    PrintStream out = new PrintStream(System.out);
    int maxDist = Integer.MAX_VALUE;

    try {/* www. j  a  v a2 s.c om*/
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption("outFile")) {
            out = new PrintStream(new File(line.getOptionValue("outFile")));
        }
        if (line.hasOption("maxDist")) {
            maxDist = Integer.valueOf(line.getOptionValue("maxDist"));
        }
        args = line.getArgs();

        if (args.length != 2) {
            throw new Exception("Unexpected number of command line arguments");
        }
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
        new HelpFormatter().printHelp("PrimerMatch <primer_list | primer_file> <seq_file>", options);
        return;
    }

    List<PatternBitMask64> primers = new ArrayList();
    if (new File(args[0]).exists()) {
        File primerFile = new File(args[0]);
        SequenceFormat seqformat = SeqUtils.guessFileFormat(primerFile);

        if (seqformat.equals(SequenceFormat.FASTA)) {
            SequenceReader reader = new SequenceReader(primerFile);
            Sequence seq;

            while ((seq = reader.readNextSequence()) != null) {
                primers.add(new PatternBitMask64(seq.getSeqString(), true, seq.getSeqName()));
            }
            reader.close();
        } else {
            BufferedReader reader = new BufferedReader(new FileReader(args[0]));
            String line;

            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (!line.equals("")) {
                    primers.add(new PatternBitMask64(line, true));
                }
            }
            reader.close();
        }
    } else {
        for (String primer : args[0].split(",")) {
            primers.add(new PatternBitMask64(primer, true));
        }
    }

    SeqReader seqReader = new SequenceReader(new File(args[1]));
    Sequence seq;
    String primerRegion;

    out.println("#seqname\tdesc\tprimer_index\tprimer_name\tposition\tmismatches\tseq_primer_region");
    while ((seq = seqReader.readNextSequence()) != null) {
        for (int index = 0; index < primers.size(); index++) {
            PatternBitMask64 primer = primers.get(index);
            BitVector64Result results = BitVector64.process(seq.getSeqString().toCharArray(), primer, maxDist);

            for (BitVector64Match result : results.getResults()) {
                primerRegion = seq.getSeqString().substring(
                        Math.max(0, result.getPosition() - primer.getPatternLength()), result.getPosition());

                if (result.getPosition() < primer.getPatternLength()) {
                    for (int pad = result.getPosition(); pad < primer.getPatternLength(); pad++) {
                        primerRegion = "x" + primerRegion;
                    }
                }

                out.println(seq.getSeqName() + "\t" + seq.getDesc() + "\t" + (index + 1) + "\t"
                        + primer.getPrimerName() + "\t" + result.getPosition() + "\t" + result.getScore() + "\t"
                        + primerRegion);
            }
        }
    }
    out.close();
    seqReader.close();
}

From source file:at.tuwien.ifs.somtoolbox.apps.helper.VectorFileLabelLister.java

public static void main(String[] args) throws IOException {
    // register and parse all options
    JSAPResult config = OptionFactory.parseResults(args, OPTIONS);

    String inputVectorFileName = AbstractOptionFactory.getFilePath(config, "input");
    String outputFileName = AbstractOptionFactory.getFilePath(config, "output");

    PrintStream out;//w  w w . jav  a2 s.c o  m
    if (StringUtils.isBlank(outputFileName)) {
        out = System.out;
    } else {
        out = new PrintStream(outputFileName);
    }

    InputData data = InputDataFactory.open(inputVectorFileName);
    String[] labels = data.getLabels();
    Arrays.sort(labels);
    for (String s : labels) {
        out.println(s);
    }
    out.close();
}

From source file:Redirect.java

public static void main(String[] argv) throws IOException {
    //+/*from w ww  .  j  a  v  a 2 s . co m*/
    String LOGFILENAME = "error.log";
    System.setErr(new PrintStream(new FileOutputStream(LOGFILENAME)));
    System.out.println("Please look for errors in " + LOGFILENAME);
    // Now assume this is somebody else's code; you'll see it writing to
    // stderr...
    int[] a = new int[5];
    a[10] = 0; // here comes an ArrayIndexOutOfBoundsException
    //-
}

From source file:mjc.ARMMain.java

public static void main(String[] args) {

    for (String arg : args) {
        if (!arg.startsWith("-")) { // ignore flags
            try {
                File in = new File(arg);
                File out = new File(FilenameUtils.removeExtension(in.getName()) + ".s");
                compile(new FileInputStream(in), new PrintStream(out));
            } catch (FileNotFoundException e) {
                System.err.println("Error: " + e.getMessage());
                System.exit(1);/*from   ww w  .  j  a  va 2s  .c  o m*/
            } catch (Throwable t) {
                System.err.println("Could not compile: " + t.getMessage());
                System.exit(1);
            }
        }
    }

    // All went well, exit with status 0.
    System.exit(0);

}

From source file:com.spotify.helios.Utils.java

public static ByteArrayOutputStream main(final List<String> args) throws Exception {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ByteArrayOutputStream err = new ByteArrayOutputStream();
    final CliMain main = new CliMain(new PrintStream(out), new PrintStream(err),
            args.toArray(new String[args.size()]));
    main.run();//from  ww  w.j a  v a 2s  .co  m
    return out;
}

From source file:MainProgram.MainProgram.java

public static void main(String[] args) throws InterruptedException, FileNotFoundException {
    MainFrame mainFrame = new MainFrame();
    errorLog = new PrintStream(file);
    try {//  w  w  w.  j  ava 2s .co m
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
            | UnsupportedLookAndFeelException ex) {
        ex.printStackTrace(errorLog);
        Logger.getLogger(MainProgram.class.getName()).log(Level.SEVERE, null, ex);
    }
    SwingUtilities.updateComponentTreeUI(mainFrame);
    mainFrame.setVisible(true);
    mainFrame.setSize(445, 415);
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setResizable(false);

}

From source file:com.muni.fi.pa165.survive.rest.client.SurviveRESTClient.java

public static void main(String[] args) {

    File file = new File("err.txt");
    FileOutputStream fos = null;//from ww  w. j a v  a  2 s .c  o m
    try {
        fos = new FileOutputStream(file);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(SurviveRESTClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    PrintStream ps = new PrintStream(fos);
    System.setErr(ps);

    CommandLineParser parser = new PosixParser();
    Options options = OptionsProvider.getInstance().getOptions();

    try {
        CommandLine line = parser.parse(options, args);
        List<String> validate = CommandLineValidator.validate(line);
        if (!validate.isEmpty()) {
            System.out.println("The following errors occured when parsing the command:");

            for (String string : validate) {
                System.out.println(string);
            }

            System.out.println("");
            printHelp(options);
            System.exit(1);
        }

        if (line.hasOption("h")) {
            printHelp(options);
            System.exit(0);
        }

        CustomRestService crudService;

        String operation = line.getOptionValue("o");

        // weapon mode
        if (line.hasOption("w")) {
            crudService = new WeaponServiceImpl();
            switch (operation) {
            case "C": {
                WeaponDto dto = DtoBuilder.getWeaponDto(line);
                Object byId = crudService.create(dto);
                printEntity(crudService.getResponse(), "Creating a weapon", byId);
                break;
            }
            case "R": {
                Long id = Long.parseLong(line.getOptionValue("i"));
                Object byId = crudService.getById(id);
                printEntity(crudService.getResponse(), "Reading a weapon with id " + id, byId);
                break;
            }
            case "U": {

                WeaponDto dto = DtoBuilder.getWeaponDto(line);
                Object byId = crudService.update(dto);
                printEntity(crudService.getResponse(), "Updating a weapon with id " + line.getOptionValue("i"),
                        byId);

                break;
            }
            case "D": {
                Long id = Long.parseLong(line.getOptionValue("i"));
                Response delete = crudService.delete(id);
                printEntity(crudService.getResponse(), "Deleting a weapon with id " + line.getOptionValue("i"),
                        crudService.getResponse().getStatusInfo());
                break;
            }
            case "A":
                List<AbstractDto> all = crudService.getAll();
                printEntities(crudService.getResponse(), "Reading all weapons", all);

                break;
            }
        } else if (line.hasOption("a")) {
            crudService = new AreaServiceImpl();
            switch (operation) {
            case "C": {
                AreaDto dto = DtoBuilder.getAreaDto(line);
                Object byId = crudService.create(dto);
                printEntity(crudService.getResponse(), "Creating an area", byId);
                break;
            }
            case "R": {
                Long id = Long.parseLong(line.getOptionValue("i"));
                Object byId = crudService.getById(id);
                printEntity(crudService.getResponse(), "Reading an area with id " + id, byId);
                break;
            }
            case "U": {
                AreaDto dto = DtoBuilder.getAreaDto(line);
                Object byId = crudService.update(dto);
                printEntity(crudService.getResponse(), "Updating an area with id " + line.getOptionValue("i"),
                        byId);
                break;
            }
            case "D": {
                Long id = Long.parseLong(line.getOptionValue("i"));
                Object byId = crudService.delete(id);
                printEntity(crudService.getResponse(), "Deleting an area with id " + line.getOptionValue("i"),
                        crudService.getResponse().getStatusInfo());
                break;
            }
            case "A":
                List<AbstractDto> all = crudService.getAll();
                printEntities(crudService.getResponse(), "Reading all areas", all);
                break;
            }
        } else {
            printHelp(options);
        }
    } catch (ParseException ex) {
        System.out.println(ex.getMessage());
        printHelp(options);
        System.exit(1);
    } catch (NumberFormatException ex) {
        System.out.println(ex.getMessage());
        printHelp(options);
        System.exit(2);
    } catch (MessageBodyProviderNotFoundException ex) {
        System.out.println("Couldn't connect to the server! Please make sure that the server side is running.");
        System.exit(3);
    } catch (ProcessingException ex) {
        System.out.println("Couldn't connect to the server! Please make sure that the server side is running.");
        System.exit(4);
    } catch (Exception ex) {
        System.out.println(
                "There was an error when connecting to the server. Please make sure that the server side is running.");
    }
}