Example usage for java.io PrintStream close

List of usage examples for java.io PrintStream close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes the stream.

Usage

From source file:org.eclipse.virgo.ide.management.remote.StandardBundleAdmin.java

@ManagedOperation(description = "Executes the given command")
public String execute(String cmdLine) {
    @SuppressWarnings("deprecation")
    StringBufferInputStream in = new StringBufferInputStream("");
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(output);

    try {//w w w. ja  v  a2  s.com
        CommandProcessor commandProcessor = this.commandProcessorTracker.getService();
        if (commandProcessor != null) {
            CommandSession commandSession = commandProcessor.createSession(in, out, out);
            Object result = null;
            try {
                result = commandSession.execute(cmdLine);
            } catch (Exception e) {
                e.printStackTrace(out);
                return output.toString();
            }
            if (result == null) {
                result = "";
            }
            return output.toString() + "\n" + result.toString();
        }
        return "No CommandProcessor registered; cannot execute commands";
    } finally {
        try {
            out.close();
            output.close();
        } catch (IOException e) {
        }
    }
}

From source file:iristk.util.Record.java

/**
 * Saves the record in JSON format to a file. If the file already exists, the content in the file is overwritten with the new record data.
 * /*from  w ww. j a v a 2 s  .  c o  m*/
 * @param inputJSONfile The file the record data are stored in
 * @throws IOException
 */
public void toJSON(File inputJSONfile) throws IOException {
    //Without the if the method will throw a NullPointer when no parent is directly specified when creating the new file
    if (inputJSONfile.getParent() != null) {
        if (!inputJSONfile.getParentFile().exists()) {
            inputJSONfile.getParentFile().mkdirs();
        }
    }
    OutputStream out = new FileOutputStream(inputJSONfile);
    final PrintStream printStream = new PrintStream(out);
    printStream.print(toJSON().toString());
    printStream.close();
}

From source file:com.blackducksoftware.tools.nrt.generator.NRTReportGenerator.java

/**
 * Generates Text output alongside the HTML
 * /*w ww. java  2 s.c om*/
 * @param projectName
 * @param outputFilename
 * @throws Exception
 */
public void generateTextReport(String projectName) throws Exception {

    PrintStream outputTextFile = null;
    FileOutputStream outputStream = null;

    try {
        File dir = new File(projectName + "_text_files\\");
        dir.mkdirs();
    } catch (SecurityException e) {
        log.error("Unable to create directory for file output", e);
    }

    for (String compKey : componentMap.keySet()) {
        ComponentModel model = componentMap.get(compKey);

        try {
            String name = model.getName() + "_" + model.getVersion();

            outputStream = new FileOutputStream(projectName + "_text_files\\" + name + ".txt");

            outputTextFile = new PrintStream(outputStream);
        } catch (FileNotFoundException e) {
            outputStream.close();
            outputTextFile.close();
            log.error("File not found: " + e.getMessage());
        }

        // Add copyrights, filepaths and license text into the next column.
        /**
         * Write out the file paths
         */
        writeOutFilePaths(compKey, outputTextFile);

        /**
         * Write out all the copy rights
         */
        writeOutCopyrights(compKey, outputTextFile);

        /**
         * Write out all the licenses
         */
        writeOutLicenseText(compKey, outputTextFile);

    } // For all component names

    // Close the stream
    outputStream.close();
    outputTextFile.close();
}

From source file:com.moscona.dataSpace.persistence.DirectoryDataStore.java

private void createSegmentIDFile() throws DataSpaceException {
    try {/*from w w w.j  a  va  2  s  .c o  m*/
        File segmentIdFile = getSegmentIdFile();
        PrintStream printStream = new PrintStream(segmentIdFile);
        try {
            printStream.println(0);
        } finally {
            printStream.close();
        }
    } catch (FileNotFoundException e) {
        throw new DataSpaceException("Exception while initializing segment ID file: " + e, e);
    }

}

From source file:com.google.cloud.dataflow.sdk.runners.worker.TextReaderTest.java

private void testNewlineHandling(String separator, boolean stripNewlines) throws Exception {
    File tmpFile = tmpFolder.newFile();
    PrintStream writer = new PrintStream(new FileOutputStream(tmpFile));
    List<String> expected = Arrays.asList("", "  hi there  ", "bob", "", "  ", "--zowie!--", "");
    List<Integer> expectedSizes = new ArrayList<>();
    for (String line : expected) {
        writer.print(line);/*from   w w w  .  j  av  a  2  s .  co  m*/
        writer.print(separator);
        expectedSizes.add(line.length() + separator.length());
    }
    writer.close();

    TextReader<String> textReader = new TextReader<>(tmpFile.getPath(), stripNewlines, null, null,
            StringUtf8Coder.of(), TextIO.CompressionType.UNCOMPRESSED);
    ExecutorTestUtils.TestReaderObserver observer = new ExecutorTestUtils.TestReaderObserver(textReader);

    List<String> actual = new ArrayList<>();
    try (Reader.ReaderIterator<String> iterator = textReader.iterator()) {
        while (iterator.hasNext()) {
            actual.add(iterator.next());
        }
    }

    if (stripNewlines) {
        assertEquals(expected, actual);
    } else {
        List<String> unstripped = new LinkedList<>();
        for (String s : expected) {
            unstripped.add(s + separator);
        }
        assertEquals(unstripped, actual);
    }

    assertEquals(expectedSizes, observer.getActualSizes());
}

From source file:com.google.appinventor.buildserver.ProjectBuilder.java

Result build(String userName, ZipFile inputZip, File outputDir, boolean isForRepl, boolean isForWireless,
        int childProcessRam, String dexCachePath) {
    try {/*w  w w .  j  av  a2s.com*/
        // Download project files into a temporary directory
        File projectRoot = createNewTempDir();
        LOG.info("temporary project root: " + projectRoot.getAbsolutePath());
        try {
            List<String> sourceFiles;
            try {
                sourceFiles = extractProjectFiles(inputZip, projectRoot);
            } catch (IOException e) {
                LOG.severe("unexpected problem extracting project file from zip");
                return Result.createFailingResult("", "Problems processing zip file.");
            }

            try {
                genYailFilesIfNecessary(sourceFiles);
            } catch (YailGenerationException e) {
                // Note that we're using a special result code here for the case of a Yail gen error.
                return new Result(Result.YAIL_GENERATION_ERROR, "", e.getMessage(), e.getFormName());
            } catch (Exception e) {
                LOG.severe("Unknown exception signalled by genYailFilesIf Necessary");
                e.printStackTrace();
                return Result.createFailingResult("", "Unexpected problems generating YAIL.");
            }

            File keyStoreFile = new File(projectRoot, KEYSTORE_FILE_NAME);
            String keyStorePath = keyStoreFile.getPath();
            if (!keyStoreFile.exists()) {
                keyStorePath = createKeyStore(userName, projectRoot, KEYSTORE_FILE_NAME);
                saveKeystore = true;
            }

            // Create project object from project properties file.
            Project project = getProjectProperties(projectRoot);

            File buildTmpDir = new File(projectRoot, "build/tmp");
            buildTmpDir.mkdirs();

            // Prepare for redirection of compiler message output
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            PrintStream console = new PrintStream(output);
            ByteArrayOutputStream errors = new ByteArrayOutputStream();
            PrintStream userErrors = new PrintStream(errors);

            Set<String> componentTypes = (isForRepl || isForWireless) ? getAllComponentTypes()
                    : getComponentTypes(sourceFiles);

            // Invoke YoungAndroid compiler
            boolean success = Compiler.compile(project, componentTypes, console, console, userErrors, isForRepl,
                    isForWireless, keyStorePath, childProcessRam, dexCachePath);
            console.close();
            userErrors.close();

            // Retrieve compiler messages and convert to HTML and log
            String srcPath = projectRoot.getAbsolutePath() + "/" + PROJECT_DIRECTORY + "/../src/";
            String messages = processCompilerOutput(output.toString(PathUtil.DEFAULT_CHARSET), srcPath);

            if (success) {
                // Locate output file
                File outputFile = new File(projectRoot, "build/deploy/" + project.getProjectName() + ".apk");
                if (!outputFile.exists()) {
                    LOG.warning("Young Android build - " + outputFile + " does not exist");
                } else {
                    outputApk = new File(outputDir, outputFile.getName());
                    Files.copy(outputFile, outputApk);
                    if (saveKeystore) {
                        outputKeystore = new File(outputDir, KEYSTORE_FILE_NAME);
                        Files.copy(keyStoreFile, outputKeystore);
                    }
                }
            }
            return new Result(success, messages, errors.toString(PathUtil.DEFAULT_CHARSET));
        } finally {
            // On some platforms (OS/X), the java.io.tmpdir contains a symlink. We need to use the
            // canonical path here so that Files.deleteRecursively will work.

            // Note (ralph):  deleteRecursively has been removed from the guava-11.0.1 lib
            // Replacing with deleteDirectory, which is supposed to delete the entire directory.
            FileUtils.deleteDirectory(new File(projectRoot.getCanonicalPath()));
        }
    } catch (Exception e) {
        e.printStackTrace();
        return Result.createFailingResult("", "Server error performing build");
    }
}

From source file:fr.gouv.culture.vitam.droid.DroidHandler.java

/**
 * Check multiples files specify exactly by the list
 * //from  w  w w.j av a 2s  .  c  om
 * @param matchedFiles
 * @param argument
 * @param task
 *            optional
 * @return a List of DroidFileFormat
 * @throws CommandExecutionException
 */
public final List<DroidFileFormat> checkFilesFormat(List<File> matchedFiles, VitamArgument argument,
        RunnerLongTask task) throws CommandExecutionException {
    if (matchedFiles.isEmpty()) {
        throw new CommandExecutionException("Resources not specified");
    }
    File dirToSearch = matchedFiles.get(0);
    String path = dirToSearch.getAbsolutePath();
    String slash = path.contains(FORWARD_SLASH) ? FORWARD_SLASH : BACKWARD_SLASH;
    String slash1 = slash;

    path = "";
    ResultPrinter resultPrinter = new ResultPrinter(vitamBinarySignatureIdentifier,
            containerSignatureDefinitions, path, slash, slash1, argument.archive, argument.checkSubFormat);

    // change System.out
    PrintStream oldOut = System.out;
    DroidFileFormatOutputStream out = new DroidFileFormatOutputStream(
            vitamBinarySignatureIdentifier.getSigFile(), argument);
    PrintStream newOut = new PrintStream(out, true);
    try {
        System.setOut(newOut);
        int currank = 0;
        for (File file : matchedFiles) {
            currank++;
            realCheck(file, resultPrinter);
            if (task != null) {
                float value = ((float) currank) / (float) matchedFiles.size();
                value *= 100;
                task.setProgressExternal((int) value);
            }
        }
    } finally {
        // reset System.out
        System.setOut(oldOut);
        newOut.close();
        newOut = null;
    }
    return out.getResult();
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.frontdesk.web.data.SessionBean.java

/** Save this object to the given path as a file */
public void serialize(String path) {
    try {//from ww  w . j a v a2s .  c om
        File file = new File(path);
        file.createNewFile();

        FileOutputStream outStream = new FileOutputStream(file);
        PrintStream printer = new PrintStream(outStream);
        //ObjectOutputStream objStream = new ObjectOutputStream(outStream);

        log.info("Wrote session definition to xml");
        printer.print(this.toString());

        printer.flush();
        printer.close();

        //objStream.writeObject(xml);
        //objStream.close();
        outStream.close();
    } catch (IOException e) {
        System.out.println("IO error writing session to a file");
        e.printStackTrace();
    }
}

From source file:com.google.cloud.dataflow.sdk.runners.worker.TextReaderTest.java

@Test
public void testNonStringCoders() throws Exception {
    File tmpFile = tmpFolder.newFile();
    PrintStream writer = new PrintStream(new FileOutputStream(tmpFile));
    List<Integer> expected = TestUtils.INTS;
    List<Integer> expectedSizes = new ArrayList<>();
    for (Integer elem : expected) {
        byte[] encodedElem = CoderUtils.encodeToByteArray(TextualIntegerCoder.of(), elem);
        writer.print(elem);// www.ja  v  a 2  s  . c  o  m
        writer.print("\n");
        expectedSizes.add(1 + encodedElem.length);
    }
    writer.close();

    TextReader<Integer> textReader = new TextReader<>(tmpFile.getPath(), true, null, null,
            TextualIntegerCoder.of(), TextIO.CompressionType.UNCOMPRESSED);
    ExecutorTestUtils.TestReaderObserver observer = new ExecutorTestUtils.TestReaderObserver(textReader);

    List<Integer> actual = new ArrayList<>();
    try (Reader.ReaderIterator<Integer> iterator = textReader.iterator()) {
        while (iterator.hasNext()) {
            actual.add(iterator.next());
        }
    }

    assertEquals(expected, actual);
    assertEquals(expectedSizes, observer.getActualSizes());
}

From source file:fr.inrialpes.exmo.align.cli.WGroupEval.java

/**
 * This does not only print the results but compute the average as well
 *
 * @param result: the vector of vector result to be printed
 *///from   w ww  .  jav  a2  s .  c o  m
public void print(Vector<Vector<Object>> result) {
    PrintStream writer = null;
    try {
        if (outputfilename == null) {
            writer = System.out;
        } else {
            writer = new PrintStream(new FileOutputStream(outputfilename));
        }

        if (type.equals("html"))
            printHTML(result, writer);
        else if (type.equals("tex"))
            printLATEX(result, writer);
        else if (type.equals("triangle"))
            printTRIANGLE(result, writer);
    } catch (Exception ex) {
        logger.debug("IGNORED Exception", ex);
    } finally {
        writer.close();
    }
}