Java Code Examples for java.io.PrintStream#close()

The following examples show how to use java.io.PrintStream#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BlockLooper.java    From AndroidPerformanceTools with Apache License 2.0 6 votes vote down vote up
private void saveLogToSdcard(BlockError blockError, File dir) {
    if (blockError == null) {
        return;
    }
    if (dir != null && dir.exists() && dir.isDirectory()) {
        String fileName = getLogFileName();
        File logFile = new File(dir, fileName);
        if (!logFile.exists()) {
            try {
                logFile.createNewFile();
                PrintStream printStream = new PrintStream(new FileOutputStream(logFile, false), true);
                blockError.printStackTrace(printStream);
                printStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
 
Example 2
Source File: NoTalkbackSlimExceptionTest.java    From rtg-tools with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public final void testNoTalkbackSlimExceptionString() {
  final ByteArrayOutputStream bos = new ByteArrayOutputStream();
  final PrintStream perr = new PrintStream(bos);
  Diagnostic.setLogStream(perr);
  try {
    final NoTalkbackSlimException e = new NoTalkbackSlimException(new RuntimeException(), ErrorType.INFO_ERROR, "really really long message");
    e.logException();
    perr.flush();
    //System.err.println(bos.toString());
    TestUtils.containsAll(bos.toString(), "really really long message");
  } finally {
    Diagnostic.setLogStream();
    perr.close();
  }

}
 
Example 3
Source File: TestLocal.java    From spork with Apache License 2.0 6 votes vote down vote up
@Test
public void testBigGroupAllWithNull() throws Throwable {

    int LOOP_COUNT = 4*1024;
    File tmpFile = File.createTempFile( this.getClass().getName(), ".txt");
    PrintStream ps = new PrintStream(new FileOutputStream(tmpFile));
    long nonNullCnt = 0;
    for(int i = 0; i < LOOP_COUNT; i++) {
    if ( i % 10 == 0 ){
           ps.println("");
    } else {
           ps.println(i);
           nonNullCnt ++;
    }
    }
    ps.close();

    assertEquals( new Double( nonNullCnt ), bigGroupAll( tmpFile) );

    tmpFile.delete();

}
 
Example 4
Source File: BamTagOfTagCounts.java    From Drop-seq with MIT License 6 votes vote down vote up
@Override
protected int doWork() {

	IOUtil.assertFileIsReadable(INPUT);
	IOUtil.assertFileIsWritable(OUTPUT);
	PrintStream out = new ErrorCheckingPrintStream(IOUtil.openFileForWriting(OUTPUT));

	writeHeader(out);

	TagOfTagResults<String,String> results= getResults(this.INPUT, this.PRIMARY_TAG, this.SECONDARY_TAG, this.FILTER_PCR_DUPLICATES, this.MINIMUM_MAPPING_QUALITY);

	for (String k: results.getKeys()) {
		Set<String> values = results.getValues(k);
		writeStats(k, values, out);
	}
	out.close();

	return(0);
}
 
Example 5
Source File: DerbyNetAutoStart.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private static boolean writeDerbyProperties( String[] properties)
{
    derbyPropertiesFile.delete();
    try
    {
        derbyPropertiesFile.createNewFile();
        PrintStream propertyWriter = new PrintStream( new FileOutputStream( derbyPropertiesFile));
        propertyWriter.print( basePropertiesSB.toString());
        for( int i = 0; i < properties.length - 1; i += 2)
            propertyWriter.println( properties[i] + "=" + properties[i + 1]);

        propertyWriter.close();
        return true;
    }
    catch( IOException ioe)
    {
        passed = false;
        System.out.println( "  Could not create gemfirexd.properties: " + ioe.getMessage());
        return false;
    }
}
 
Example 6
Source File: TestCopyFiles.java    From hadoop-gpu with Apache License 2.0 5 votes vote down vote up
static String execCmd(FsShell shell, String... args) throws Exception {
  ByteArrayOutputStream baout = new ByteArrayOutputStream();
  PrintStream out = new PrintStream(baout, true);
  PrintStream old = System.out;
  System.setOut(out);
  shell.run(args);
  out.close();
  System.setOut(old);
  return baout.toString();
}
 
Example 7
Source File: TestFilterOpNumeric.java    From spork with Apache License 2.0 5 votes vote down vote up
@Test
public void testNumericLte() throws Throwable {
    File tmpFile = File.createTempFile("test", "txt");
    PrintStream ps = new PrintStream(new FileOutputStream(tmpFile));
    for(int i = 0; i < LOOP_COUNT; i++) {
        if(i % 5 == 0) {
            ps.println(i + ":" + (double)i);
        } else if(i % 3 == 0){
            ps.println(i-1 + ":" + (double)(i));
        } else {
            ps.println(i+1 + ":" + (double)(i));
        }
    }
    ps.close();
    pig.registerQuery("A=load '"
            + Util.encodeEscape(Util.generateURI(tmpFile.toString(), pig.getPigContext()))
            + "' using " + PigStorage.class.getName() + "(':') as (a: double, b:double);");
    String query = "A = filter A by ($0 <= $1 or $0 < $1);";

    log.info(query);
    pig.registerQuery(query);
    Iterator<Tuple> it = pig.openIterator("A");
    tmpFile.delete();
    while(it.hasNext()) {
        Tuple t = it.next();
        Double first = Double.valueOf(t.get(0).toString());
        Double second = Double.valueOf(t.get(1).toString());
        assertTrue(first.compareTo(second) <= 0);
    }
}
 
Example 8
Source File: TestFilterOpNumeric.java    From spork with Apache License 2.0 5 votes vote down vote up
@Test
public void testNumericGt() throws Throwable {
    File tmpFile = File.createTempFile("test", "txt");
    PrintStream ps = new PrintStream(new FileOutputStream(tmpFile));
    for(int i = 0; i < LOOP_COUNT; i++) {
        if(i % 5 == 0) {
            ps.println(i + ":" + (double)i);
        } else {
            ps.println(i+1 + ":" + (double)(i));
        }
    }
    ps.close();
    pig.registerQuery("A=load '"
            + Util.encodeEscape(Util.generateURI(tmpFile.toString(), pig.getPigContext())) + "' using "
            + PigStorage.class.getName() + "(':') as (f1: double, f2:double);");
    String query = "A = filter A by ($0 > $1 and $0 >= $1);";

    log.info(query);
    pig.registerQuery(query);
    Iterator<Tuple> it = pig.openIterator("A");
    tmpFile.delete();
    while(it.hasNext()) {
        Tuple t = it.next();
        Double first = Double.valueOf(t.get(0).toString());
        Double second = Double.valueOf(t.get(1).toString());
        assertTrue(first.compareTo(second) > 0);
    }
}
 
Example 9
Source File: SCCServerStub.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void respond(Request request, Response response) {
    // Set some respond headers
    response.set("Content-Type", "application/json");
    long time = System.currentTimeMillis();
    response.setDate("Date", time);
    response.setDate("Last-Modified", time);
    String path = request.getURI();
    if (!path.endsWith("2")) {
        response.set("Link",
                "<" + uri + path + "2>; rel=\"last\", " +
                "<" + uri + path + "2>; rel=\"next\"");
    }
    response.set("Per-Page", "1");
    response.set("Total", "2");

    // Send file content
    try {
        String filename = path.replaceFirst("/", "").replaceFirst("\\?page=", "") + ".json";
        URL url = TestUtils.findTestData(filename);

        InputStream in = url.openStream();
        PrintStream out = response.getPrintStream();
        IOUtils.copy(in, out);
        out.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 10
Source File: SplitBamByCell.java    From Drop-seq with MIT License 5 votes vote down vote up
private void writeOutputList(final List<SAMFileInfo> writerInfoList) {
    final PrintStream out = new ErrorCheckingPrintStream(IOUtil.openFileForWriting(OUTPUT_LIST));

    for (SAMFileInfo writerInfo : writerInfoList) {
        out.println(writerInfo.getSamFile().toString());
    }

    out.close();
}
 
Example 11
Source File: TemporaryFolder.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * generate '.createdBy' file with a stack trace so tests that leak temp folders can be identified later.
 */
protected void addSourceInfo(File tempDir) throws IOException {
	PrintStream printStream = new PrintStream(new File(tempDir, ".createdBy"));
	try {
		printStream.append("This temp dir has been created from the stack below. If you want to make sure the temp folders are cleaned up after a test executed, you should add the following to your test class: \n\n");
		printStream.append("     @Rule @Inject public TemporaryFolder temporaryFolder \n\n");
		new Exception().printStackTrace(printStream);
	} finally {
		printStream.close();
	}
	
}
 
Example 12
Source File: RemoteStatistics.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static boolean stopAction() {
    RemoteMeasurementsRef stopped = currentStatRef.getAndSet(unnamed);
    PrintStream output = getOutput(stopped.name);
    try {
        stopped.stat.dump(output);
    } finally {
        if (!output.equals(System.out)) {
            output.close();
        }
    }
    return unnamed.equals(stopped);
}
 
Example 13
Source File: JFrameMasterCtrlMenuRecents.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
private void dumpRecentsToFile() {
    try {
        PrintStream printStream = new PrintStream(new FileOutputStream("../conf/master.recents"));//BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("../conf/master.recents"));
        for (String path : _recents) {
            printStream.println(path);
        }
        printStream.close();
    }
    catch (IOException e) {
        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE, "Unable to save recent files");
    }
}
 
Example 14
Source File: TransactionWriter.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
private
static
void
generate(Transaction[] transactions, File file)
{
  try
  {
    PrintStream stream = createPrintStream(file);

    stream.println("<html>");
    printHeadTag(stream);
    stream.println("<body>");

    printPreparedOn(stream);
    stream.println(TABLE_BREAK);
    printSectionHeader(stream, getSharedProperty("transaction_details"));
    printTransactions(stream, transactions);

    stream.println("</body></html>");

    stream.flush();
    stream.close();

    showSuccessMessage(file);
  }
  catch(Exception exception)
  {
    showErrorMessage(exception);
  }
}
 
Example 15
Source File: TestLocal.java    From spork with Apache License 2.0 5 votes vote down vote up
@Test
public void testBigGroupAll() throws Throwable {

    int LOOP_COUNT = 4*1024;
    File tmpFile = File.createTempFile( this.getClass().getName(), ".txt");
    PrintStream ps = new PrintStream(new FileOutputStream(tmpFile));
    for(int i = 0; i < LOOP_COUNT; i++) {
        ps.println(i);
    }
    ps.close();
    assertEquals( new Double( LOOP_COUNT ), bigGroupAll( tmpFile) );
    tmpFile.delete();

}
 
Example 16
Source File: CDSTestUtils.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void writeFile(File file, String content) throws Exception {
    FileOutputStream fos = new FileOutputStream(file);
    PrintStream ps = new PrintStream(fos);
    ps.print(content);
    ps.close();
    fos.close();
}
 
Example 17
Source File: AbstractWalkmodExecutionTest.java    From walkmod-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String run(String[] args) throws Exception {

		ByteArrayOutputStream mem = new ByteArrayOutputStream();
		BufferedOutputStream stream = new BufferedOutputStream(mem);

		PrintStream ps = new PrintStream(stream);
		PrintStream old = System.out;
		System.setOut(ps);

		WalkModFacade.log = Logger.getLogger(WalkModFacade.class.getName());
		WalkModFacade.log.removeAllAppenders();
		
		ConfigurationImpl.log = Logger.getLogger(ConfigurationImpl.class.getName());
		ConfigurationImpl.log.removeAllAppenders();
        
		ConsoleAppender appender = new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN));
		appender.setName("stdout");
		WalkModFacade.log.addAppender(appender);
		ConfigurationImpl.log.addAppender(appender);
		
		String result = "";
		try {
			WalkModDispatcher.main(args);
			stream.flush();
			result = mem.toString();

		} finally {
			System.setOut(old);
			ps.close();
			stream.close();
			mem.close();
		}

		return result;
	}
 
Example 18
Source File: JarReorder.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
private void run(String args[]) {

        int arglen = args.length;
        int argpos = 0;

        // Look for "-o outputfilename" option
        if (arglen > 0) {
            if (arglen >= 2 && args[0].equals("-o")) {
                try {
                    out = new PrintStream(new FileOutputStream(args[1]));
                } catch (FileNotFoundException e) {
                    System.err.println("Error: " + e.getMessage());
                    e.printStackTrace(System.err);
                    System.exit(1);
                }
                argpos += 2;
                arglen -= 2;
            } else {
                System.err.println("Error: Illegal arg count");
                System.exit(1);
            }
        } else {
            out = System.out;
        }

        // Should be 2 or more args left
        if (arglen <= 2) {
            usage();
            System.exit(1);
        }

        // Read the ordered set of files to be included in rt.jar.
        // Read the set of files/directories to be excluded from rt.jar.
        String classListFile = args[argpos];
        String excludeListFile = args[argpos + 1];
        argpos += 2;
        arglen -= 2;

        // Create 2 lists and a set of processed files
        List<String> orderList = readListFromFile(classListFile, true);
        List<String> excludeList = readListFromFile(excludeListFile, false);
        Set<String> processed = new HashSet<String>();

        // Create set of all files and directories excluded, then expand
        //   that list completely
        Set<String> excludeSet = new HashSet<String>(excludeList);
        Set<String> allFilesExcluded = expand(null, excludeSet, processed);

        // Indicate all these have been processed, orderList too, kept to end.
        processed.addAll(orderList);

        // The remaining arguments are names of files/directories to be included
        // in the jar file.
        Set<String> inputSet = new HashSet<String>();
        for (int i = 0; i < arglen; ++i) {
            String name = args[argpos + i];
            name = cleanPath(new File(name));
            if ( name != null && name.length() > 0 && !inputSet.contains(name) ) {
                inputSet.add(name);
            }
        }

        // Expand file/directory input so we get a complete set (except ordered)
        //   Should be everything not excluded and not in order list.
        Set<String> allFilesIncluded = expand(null, inputSet, processed);

        // Create simple sorted list so we can add ordered items at end.
        List<String> allFiles = new ArrayList<String>(allFilesIncluded);
        Collections.sort(allFiles);

        // Now add the ordered set to the end of the list.
        // Add in REVERSE ORDER, so that the first element is closest to
        // the end (and the index).
        for (int i = orderList.size() - 1; i >= 0; --i) {
            String s = orderList.get(i);
            if (allFilesExcluded.contains(s)) {
                // Disable this warning until 8005688 is fixed
                // System.err.println("Included order file " + s
                //    + " is also excluded, skipping.");
            } else if (new File(s).exists()) {
                allFiles.add(s);
            } else {
                System.err.println("Included order file " + s
                    + " missing, skipping.");
            }
        }

        // Print final results.
        for (String str : allFiles) {
            out.println(str);
        }
        out.flush();
        out.close();
    }
 
Example 19
Source File: Generator.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * @throws IOException
 * 
 */

private void writeStyles( ) throws IOException
{
	writeIndexEntry(
			"Predefined Styles",
			"styles",
			"Styles defined by BIRT, usually as a \"default style\" for an element or slot." );

	File output = makeFile( null, "styles.html" );
	writer = new PrintStream( new FileOutputStream( output ) );

	Properties selectors = new Properties( );
	try
	{
		InputStream is = new BufferedInputStream( new FileInputStream(
				templateDir + "/style/selectors.properties" ) );
		selectors.load( is );
	}
	catch ( IOException ex )
	{
		System.out.println( "Can not read in \"selectors.properties\". ");
	}

	writeln( "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 transitional//EN\">" );
	write( "<html>\n<head>\n<title>" );
	writeln( " Element (Eclipse BIRT ROM Documentation)</title>" );
	writeln( "<link rel=\"stylesheet\" href=\"style/style.css\" type=\"text/css\"/>" );
	writeln( "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">" );
	writeln( "</head>\n<body>" );
	writeln( "<p class=\"title\">Eclipse BIRT Report Object Model (ROM)</p>" );
	writeln( "<p class=\"subtitle\">Predefined Styles</p>" );
	writeln( "<h1>Predefined Styles</h1>\n<table class=\"summary-table\">" );

	MetaDataDictionary dict = MetaDataDictionary.getInstance( );
	ArrayList list = new ArrayList( );
	list.addAll( dict.getPredefinedStyles( ) );
	Collections.sort( list, new StyleComparator( ) );
	Iterator iter = list.iterator( );
	while ( iter.hasNext( ) )
	{
		PredefinedStyle style = (PredefinedStyle) iter.next( );
		write( "<tr><td><a name=\"" );
		write( style.getName( ) );
		write( "\">" );
		write( style.getName( ) );
		write( "</a></td>\n<td>" );
		
		String description = selectors.getProperty( style.getName() );
		if( description == null )
		{
			System.err.println( "Missing selector description for " + style.getName() );
		}
		
		write( description );
		writeln( "</td></tr>" );
	}
	finishSummaryTable( );
	writeFooter( );
	writer.close( );
}
 
Example 20
Source File: RequiredModelMBean.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/*************************************/


    private synchronized void writeToLog(String logFileName,
                                         String logEntry) throws Exception {

        if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
            MODELMBEAN_LOGGER.logp(Level.FINER,
                    RequiredModelMBean.class.getName(),
                "writeToLog(String, String)",
                "Notification Logging to " + logFileName + ": " + logEntry);
        }
        if ((logFileName == null) || (logEntry == null)) {
            if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
                MODELMBEAN_LOGGER.logp(Level.FINER,
                        RequiredModelMBean.class.getName(),
                    "writeToLog(String, String)",
                    "Bad input parameters, will not log this entry.");
            }
            return;
        }

        FileOutputStream fos = new FileOutputStream(logFileName, true);
        try {
            PrintStream logOut = new PrintStream(fos);
            logOut.println(logEntry);
            logOut.close();
            if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
                MODELMBEAN_LOGGER.logp(Level.FINER,
                        RequiredModelMBean.class.getName(),
                    "writeToLog(String, String)","Successfully opened log " +
                        logFileName);
            }
        } catch (Exception e) {
            if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
                MODELMBEAN_LOGGER.logp(Level.FINER,
                    RequiredModelMBean.class.getName(),
                        "writeToLog(String, String)",
                        "Exception " + e.toString() +
                        " trying to write to the Notification log file " +
                        logFileName);
            }
            throw e;
        } finally {
            fos.close();
        }
    }