Java Code Examples for java.io.FileOutputStream

The following examples show how to use java.io.FileOutputStream. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: jdk8u_jdk   Source File: BandStructure.java    License: GNU General Public License v2.0 6 votes vote down vote up
static OutputStream getDumpStream(String name, int seq, String ext, Object b) throws IOException {
    if (dumpDir == null) {
        dumpDir = File.createTempFile("BD_", "", new File("."));
        dumpDir.delete();
        if (dumpDir.mkdir())
            Utils.log.info("Dumping bands to "+dumpDir);
    }
    name = name.replace('(', ' ').replace(')', ' ');
    name = name.replace('/', ' ');
    name = name.replace('*', ' ');
    name = name.trim().replace(' ','_');
    name = ((10000+seq) + "_" + name).substring(1);
    File dumpFile = new File(dumpDir, name+ext);
    Utils.log.info("Dumping "+b+" to "+dumpFile);
    return new BufferedOutputStream(new FileOutputStream(dumpFile));
}
 
Example 2
Source Project: jdk8u60   Source File: TestLibrary.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void copyFile(File srcFile, File dstFile)
    throws IOException
{
    FileInputStream src = new FileInputStream(srcFile);
    FileOutputStream dst = new FileOutputStream(dstFile);

    byte[] buf = new byte[32768];
    while (true) {
        int count = src.read(buf);
        if (count < 0) {
            break;
        }
        dst.write(buf, 0, count);
    }

    dst.close();
    src.close();
}
 
Example 3
Source Project: teiid-spring-boot   Source File: ZipUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static File unzipContents(File in, File out) throws FileNotFoundException, IOException {
    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(new FileInputStream(in));
    ZipEntry ze = zis.getNextEntry();
    while (ze != null) {
        String fileName = ze.getName();
        File newFile = new File(out, fileName);
        if (ze.isDirectory()) {
            newFile.mkdirs();
        } else {
            new File(newFile.getParent()).mkdirs();
            FileOutputStream fos = new FileOutputStream(newFile);
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
        }
        zis.closeEntry();
        ze = zis.getNextEntry();
    }
    zis.close();
    return out;
}
 
Example 4
Source Project: GreenBits   Source File: BuildCheckpoints.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void writeBinaryCheckpoints(TreeMap<Integer, StoredBlock> checkpoints, File file) throws Exception {
    final FileOutputStream fileOutputStream = new FileOutputStream(file, false);
    MessageDigest digest = Sha256Hash.newDigest();
    final DigestOutputStream digestOutputStream = new DigestOutputStream(fileOutputStream, digest);
    digestOutputStream.on(false);
    final DataOutputStream dataOutputStream = new DataOutputStream(digestOutputStream);
    dataOutputStream.writeBytes("CHECKPOINTS 1");
    dataOutputStream.writeInt(0);  // Number of signatures to read. Do this later.
    digestOutputStream.on(true);
    dataOutputStream.writeInt(checkpoints.size());
    ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE);
    for (StoredBlock block : checkpoints.values()) {
        block.serializeCompact(buffer);
        dataOutputStream.write(buffer.array());
        buffer.position(0);
    }
    dataOutputStream.close();
    Sha256Hash checkpointsHash = Sha256Hash.wrap(digest.digest());
    System.out.println("Hash of checkpoints data is " + checkpointsHash);
    digestOutputStream.close();
    fileOutputStream.close();
    System.out.println("Checkpoints written to '" + file.getCanonicalPath() + "'.");
}
 
Example 5
Source Project: lavaplayer   Source File: NativeLibraryLoader.java    License: Apache License 2.0 6 votes vote down vote up
private Path extractLibraryFromResources(SystemType systemType) {
  try (InputStream libraryStream = binaryProvider.getLibraryStream(systemType, libraryName)) {
    if (libraryStream == null) {
      throw new UnsatisfiedLinkError("Required library was not found");
    }

    Path extractedLibraryPath = prepareExtractionDirectory().resolve(systemType.formatLibraryName(libraryName));

    try (FileOutputStream fileStream = new FileOutputStream(extractedLibraryPath.toFile())) {
      IOUtils.copy(libraryStream, fileStream);
    }

    return extractedLibraryPath;
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 6
@Override
public void createArchive(String path, String archiveName, Manifest manifest) {
  File file = new File(getAbsolutePath(path), archiveName);
  try {
    if (!(file.createNewFile() || file.isFile())) {
      throw new IOException("Cannot create file " + file);
    }

    FileOutputStream fileStream = new FileOutputStream(file);
    @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
    ZipOutputStream zipStream = manifest != null ? new JarOutputStream(fileStream, manifest) : new ZipOutputStream(fileStream);
    mapArchiveStreams.put(file.getPath(), zipStream);
  } catch (IOException ex) {
    DecompilerContext.getLogger().writeMessage("Cannot create archive " + file, ex);
  }
}
 
Example 7
Source Project: flink   Source File: PackagedProgramTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExtractContainedLibraries() throws Exception {
	String s = "testExtractContainedLibraries";
	byte[] nestedJarContent = s.getBytes(ConfigConstants.DEFAULT_CHARSET);
	File fakeJar = temporaryFolder.newFile("test.jar");
	try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fakeJar))) {
		ZipEntry entry = new ZipEntry("lib/internalTest.jar");
		zos.putNextEntry(entry);
		zos.write(nestedJarContent);
		zos.closeEntry();
	}

	final List<File> files = PackagedProgram.extractContainedLibraries(fakeJar.toURI().toURL());
	Assert.assertEquals(1, files.size());
	Assert.assertArrayEquals(nestedJarContent, Files.readAllBytes(files.iterator().next().toPath()));
}
 
Example 8
Source Project: Viewer   Source File: MyRenderer.java    License: Apache License 2.0 6 votes vote down vote up
public void rawByteArray2RGBABitmap2(FileOutputStream b)
{
	int yuvi = yuv_w * yuv_h;
	int uvi = 0;
	byte[] yuv = new byte[yuv_w * yuv_h * 3 / 2];
	System.arraycopy(y, 0, yuv, 0, yuvi);
	for (int i = 0; i < yuv_h / 2; i++)
	{
		for (int j = 0; j < yuv_w / 2; j++)
		{
			yuv[yuvi++] = v[uvi];
			yuv[yuvi++] = u[uvi++];
		}
	}
	YuvImage yuvImage = new YuvImage(yuv, ImageFormat.NV21, yuv_w, yuv_h, null);
	Rect rect = new Rect(0, 0, yuv_w, yuv_h);
	yuvImage.compressToJpeg(rect, 100, b);
}
 
Example 9
private Uri getUriFromRemote(String path) {
    File file = getTmpFile();
    if (file == null)
        return null;
    try {
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        connection.setRequestProperty("Connection", "close");
        connection.setConnectTimeout(5000);
        connection.connect();
        InputStream input = connection.getInputStream();
        FileOutputStream outStream = new FileOutputStream(file);
        copyFile(input, outStream);
        return getProvidedFileUri(file);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 10
Source Project: presto   Source File: FileBackupStore.java    License: Apache License 2.0 6 votes vote down vote up
private static void copyFile(File source, File target)
        throws IOException
{
    try (InputStream in = new FileInputStream(source);
            FileOutputStream out = new FileOutputStream(target)) {
        byte[] buffer = new byte[128 * 1024];
        while (true) {
            int n = in.read(buffer);
            if (n == -1) {
                break;
            }
            out.write(buffer, 0, n);
        }
        out.flush();
        out.getFD().sync();
    }
}
 
Example 11
Source Project: jdk8u60   Source File: CrossRealm.java    License: GNU General Public License v2.0 6 votes vote down vote up
static void xRealmAuth() throws Exception {
    Security.setProperty("auth.login.defaultCallbackHandler", "CrossRealm");
    System.setProperty("java.security.auth.login.config", "jaas-localkdc.conf");
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    FileOutputStream fos = new FileOutputStream("jaas-localkdc.conf");
    fos.write(("com.sun.security.jgss.krb5.initiate {\n" +
            "    com.sun.security.auth.module.Krb5LoginModule\n" +
            "    required\n" +
            "    principal=dummy\n" +
            "    doNotPrompt=false\n" +
            "    useTicketCache=false\n" +
            "    ;\n" +
            "};").getBytes());
    fos.close();

    GSSManager m = GSSManager.getInstance();
    m.createContext(
            m.createName("[email protected]", GSSName.NT_HOSTBASED_SERVICE),
            GSSUtil.GSS_KRB5_MECH_OID,
            null,
            GSSContext.DEFAULT_LIFETIME).initSecContext(new byte[0], 0, 0);
}
 
Example 12
static void setUp() throws Exception {
    testarray = new float[1024];
    for (int i = 0; i < 1024; i++) {
        double ii = i / 1024.0;
        ii = ii * ii;
        testarray[i] = (float)Math.sin(10*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(1.731 + 2*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(0.231 + 6.3*ii*2*Math.PI);
        testarray[i] *= 0.3;
    }
    test_byte_array = new byte[testarray.length*2];
    AudioFloatConverter.getConverter(format).toByteArray(testarray, test_byte_array);
    test_file = File.createTempFile("test", ".raw");
    FileOutputStream fos = new FileOutputStream(test_file);
    fos.write(test_byte_array);
}
 
Example 13
Source Project: spork   Source File: TestLocal2.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPig800Sort() throws Exception {
    // Regression test for Pig-800
    File fp1 = File.createTempFile("test", "txt");
    PrintStream ps = new PrintStream(new FileOutputStream(fp1));

    ps.println("1\t1}");
    ps.close();

    pig.registerQuery("A = load '"
            + Util.generateURI(fp1.toString(), pig.getPigContext())
            + "'; ");
    pig.registerQuery("B = foreach A generate flatten("
            + Pig800Udf.class.getName() + "($0));");
    pig.registerQuery("C = order B by $0;");

    Iterator<Tuple> iter = pig.openIterator("C");
    // Before PIG-800 was fixed this went into an infinite loop, so just
    // managing to open the iterator is sufficient.
    fp1.delete();

}
 
Example 14
Source Project: neoscada   Source File: DebianPackageWriter.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public DebianPackageWriter ( final OutputStream stream, final GenericControlFile packageControlFile, final TimestampProvider timestampProvider ) throws IOException
{
    this.packageControlFile = packageControlFile;
    this.timestampProvider = timestampProvider;
    if ( getTimestampProvider () == null )
    {
        throw new IllegalArgumentException ( "'timestampProvider' must not be null" );
    }
    BinaryPackageControlFile.validate ( packageControlFile );

    this.ar = new ArArchiveOutputStream ( stream );

    this.ar.putArchiveEntry ( new ArArchiveEntry ( "debian-binary", this.binaryHeader.length, 0, 0, AR_ARCHIVE_DEFAULT_MODE, getTimestampProvider ().getModTime () / 1000 ) );
    this.ar.write ( this.binaryHeader );
    this.ar.closeArchiveEntry ();

    this.dataTemp = File.createTempFile ( "data", null );

    this.dataStream = new TarArchiveOutputStream ( new GZIPOutputStream ( new FileOutputStream ( this.dataTemp ) ) );
    this.dataStream.setLongFileMode ( TarArchiveOutputStream.LONGFILE_GNU );
}
 
Example 15
Source Project: OpenEphyra   Source File: ASSERT.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
	 * Creates a temporary file containing the sentences to be processed by ASSERT.
	 * 
	 * @param ss sentences to be parsed
	 * @return input file
	 */
	private static File createInputFile(String[] ss) throws Exception {
		try {
			File input = File.createTempFile("assert", ".input", new File(ASSERT_DIR + "/scripts"));
//			input.deleteOnExit();
			PrintWriter pw = new PrintWriter(new BufferedWriter(
				new OutputStreamWriter(new FileOutputStream(input), "ISO-8859-1")));
			
			for (String sentence : ss) {
				pw.println(sentence);
				if (pw.checkError()) throw new IOException();
			}
			
			pw.close();
			if (pw.checkError()) throw new IOException();
			
			return input;
		} catch (IOException e) {
			throw new IOException("Failed to create input file.");
		}
	}
 
Example 16
@Test
public void test() throws Exception {
	assertThat(this.splitter, instanceOf(FileSplitter.class));
	assertSame(this.splitter, TestUtils.getPropertyValue(this.consumer, "handler"));
	File file = new File(System.getProperty("java.io.tmpdir") + File.separator + "splitter.proc.test");
	FileOutputStream fos = new FileOutputStream(file);
	fos.write("hello\nworld\n".getBytes());
	fos.close();
	this.channels.input().send(new GenericMessage<>(file));
	Message<?> m = this.collector.forChannel(this.channels.output()).poll(10, TimeUnit.SECONDS);
	assertNotNull(m);
	assertNull((m.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER)));
	assertThat(m, hasPayload("hello"));
	assertThat(this.collector.forChannel(this.channels.output()), receivesPayloadThat(is("world")));
	file.delete();
}
 
Example 17
Source Project: Silence   Source File: SaveAttachmentTask.java    License: GNU General Public License v3.0 6 votes vote down vote up
private boolean saveAttachment(Context context, MasterSecret masterSecret, Attachment attachment) throws IOException {
  String contentType      = MediaUtil.getCorrectedMimeType(attachment.contentType);
  File mediaFile          = constructOutputFile(contentType, attachment.date);
  InputStream inputStream = PartAuthority.getAttachmentStream(context, masterSecret, attachment.uri);

  if (inputStream == null) {
    return false;
  }

  OutputStream outputStream = new FileOutputStream(mediaFile);
  Util.copy(inputStream, outputStream);

  MediaScannerConnection.scanFile(context, new String[]{mediaFile.getAbsolutePath()},
                                  new String[]{contentType}, null);

  return true;
}
 
Example 18
Source Project: android-wear-gopro-remote   Source File: Logger.java    License: Apache License 2.0 6 votes vote down vote up
public static void log2file(String tag, String msg, String fileName, Throwable e) {

        try {
            getLogFolder();

            Date now = new Date();

            File file = new File(sLogsFolder, String.format(fileName, LOG_DATE_FORMAT.format(now)));

            FileOutputStream os = new FileOutputStream(file, true);
            try (OutputStreamWriter writer = new OutputStreamWriter(os)) {
                writer.append(SIMPLE_DATE_FORMAT.format(now));
                writer.append("\t");
                writer.append(tag);
                writer.append("\t");
                writer.append(msg);
                writer.append("\t");
                if (e != null)
                    writer.append(e.toString());
                writer.append("\n");
                writer.flush();
            }
        } catch (IOException ex) {
            //Log.w(TAG, "log2file failed:", ex);
        }
    }
 
Example 19
Source Project: jeewx   Source File: MigrateForm.java    License: Apache License 2.0 6 votes vote down vote up
public static void generateXmlDataOutFlieContent(List<DBTable> dbTables, String parentDir) throws BusinessException{
	File file = new File(parentDir);
	if (!file.exists()) {
		buildFile(parentDir, true);
	}
	try {
		XStream xStream = new XStream();
		xStream.registerConverter(new NullConverter());
		xStream.processAnnotations(DBTable.class);
		FileOutputStream outputStream = new FileOutputStream(buildFile(parentDir+"/migrateExport.xml", false));
		Writer writer = new OutputStreamWriter(outputStream, "UTF-8");
		writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n");
		xStream.toXML(dbTables, writer);
	} catch (Exception e) {
		throw new BusinessException(e.getMessage());
	}
}
 
Example 20
Source Project: hottub   Source File: Read.java    License: GNU General Public License v2.0 6 votes vote down vote up
static void setUp() throws Exception {
    testarray = new float[1024];
    for (int i = 0; i < 1024; i++) {
        double ii = i / 1024.0;
        ii = ii * ii;
        testarray[i] = (float)Math.sin(10*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(1.731 + 2*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(0.231 + 6.3*ii*2*Math.PI);
        testarray[i] *= 0.3;
    }
    test_byte_array = new byte[testarray.length*2];
    AudioFloatConverter.getConverter(format).toByteArray(testarray, test_byte_array);
    test_file = File.createTempFile("test", ".raw");
    FileOutputStream fos = new FileOutputStream(test_file);
    fos.write(test_byte_array);
}
 
Example 21
public void writeToFile(String data, String filename, String tag) {
    try {
        File root = Environment.getExternalStorageDirectory();
        File dir = new File (root.getAbsolutePath() + "/foldercustom");
        dir.mkdirs();
        File file = new File(dir, filename);
        FileOutputStream f = new FileOutputStream(file);
        PrintWriter pw = new PrintWriter(f);
        pw.println(data);
        pw.flush();
        pw.close();
        f.close();
    }
    catch (IOException e) {
        Log.e(tag, "File write failed: " + e.toString());
    }
}
 
Example 22
Source Project: sling-samples   Source File: ThumbnailGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void createThumbnail(Node image, int scalePercent, String mimeType, String suffix) throws Exception {
       final File tmp = File.createTempFile(getClass().getSimpleName(), suffix);
       try {
           scale(image.getProperty("jcr:data").getStream(), scalePercent, new FileOutputStream(tmp), suffix);

           // Create thumbnail node and set the mandatory properties
           Node thumbnailFolder = getThumbnailFolder(image);
           Node thumbnail = thumbnailFolder.addNode(image.getParent().getName() + "_" + scalePercent + suffix, "nt:file");
           Node contentNode = thumbnail.addNode("jcr:content", "nt:resource");
           contentNode.setProperty("jcr:data", new FileInputStream(tmp));
           contentNode.setProperty("jcr:lastModified", Calendar.getInstance());
           contentNode.setProperty("jcr:mimeType", mimeType);

           session.save();

           log.info("Created thumbnail " + contentNode.getPath());
       } finally {
           if(tmp != null) {
               tmp.delete();
           }
       }

}
 
Example 23
Source Project: cordova-social-vk   Source File: VKUploadImage.java    License: Apache License 2.0 6 votes vote down vote up
public File getTmpFile() {
    Context ctx = VKUIHelper.getApplicationContext();
    File outputDir = null;
    if (ctx != null) {
        outputDir = ctx.getExternalCacheDir();
        if (outputDir == null || !outputDir.canWrite())
            outputDir = ctx.getCacheDir();
    }
    File tmpFile = null;
    try {
        tmpFile = File.createTempFile("tmpImg", String.format(".%s", mParameters.fileExtension()), outputDir);
        FileOutputStream fos = new FileOutputStream(tmpFile);
        if (mParameters.mImageType == VKImageParameters.VKImageType.Png)
            mImageData.compress(Bitmap.CompressFormat.PNG, 100, fos);
        else
            mImageData.compress(Bitmap.CompressFormat.JPEG, (int) (mParameters.mJpegQuality * 100), fos);
        fos.close();
    } catch (IOException ignored) {
        if (VKSdk.DEBUG)
            ignored.printStackTrace();
    }
    return tmpFile;
}
 
Example 24
Source Project: SmartPaperScan   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
public static String exportResource(Context context, int resourceId, String dirname) {
    String fullname = context.getResources().getString(resourceId);
    String resName = fullname.substring(fullname.lastIndexOf("/") + 1);
    try {
        InputStream is = context.getResources().openRawResource(resourceId);
        File resDir = context.getDir(dirname, Context.MODE_PRIVATE);
        File resFile = new File(resDir, resName);

        FileOutputStream os = new FileOutputStream(resFile);

        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        is.close();
        os.close();

        return resFile.getAbsolutePath();
    } catch (IOException e) {
        e.printStackTrace();
        throw new CvException("Failed to export resource " + resName
                + ". Exception thrown: " + e);
    }
}
 
Example 25
Source Project: JDA   Source File: SimpleLogger.java    License: Apache License 2.0 6 votes vote down vote up
private static PrintStream computeTargetStream(String logFile) {
    if ("System.err".equalsIgnoreCase(logFile))
        return System.err;
    else if ("System.out".equalsIgnoreCase(logFile)) {
        return System.out;
    } else {
        try {
            FileOutputStream fos = new FileOutputStream(logFile);
            PrintStream printStream = new PrintStream(fos);
            return printStream;
        } catch (FileNotFoundException e) {
            Util.report("Could not open [" + logFile + "]. Defaulting to System.err", e);
            return System.err;
        }
    }
}
 
Example 26
Source Project: sc2gears   Source File: SettingsApiImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean saveProperties() {
	// If no property is set...
	if ( properties.isEmpty() ) {
		if ( settingsFile.exists() )
			// ...and there are persisted properties, delete them
			return settingsFile.delete();
		else
			// ...and there are no persisted properties, we're done
			return true;
	}
	
	try ( final FileOutputStream output = new FileOutputStream( settingsFile ) ) {
		properties.storeToXML( output, "Saved at " + new Date() );
		return true;
	} catch ( final Exception e ) {
		System.err.println( "Failed to save plugin properties!" );
		e.printStackTrace( System.err );
		return false;
	}
}
 
Example 27
Source Project: HouSi   Source File: SourceApiHelper.java    License: Apache License 2.0 6 votes vote down vote up
private static File mergeFiles(File outFile, List<File> files) {
    FileChannel outChannel = null;
    try {
        outChannel = new FileOutputStream(outFile).getChannel();
        for (File file : files) {
            FileChannel fc = new FileInputStream(file).getChannel();
            ByteBuffer bb = ByteBuffer.allocate(1024);
            while (fc.read(bb) != -1) {
                bb.flip();
                outChannel.write(bb);
                bb.clear();
            }
            fc.close();
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        try {
            if (outChannel != null) {
                outChannel.close();
            }
        } catch (IOException ignore) {
        }
    }
    return outFile;
}
 
Example 28
@Test
public void testParagraphBackgroundEventListener() throws DocumentException, FileNotFoundException
{
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(RESULT_FOLDER, "document-with-paragraph-backgrounds.pdf")));
    ParagraphBackground border = new ParagraphBackground();
    writer.setPageEvent(border);
    document.open();
    document.add(new Paragraph("Hello,"));
    document.add(new Paragraph("In this document, we'll add several paragraphs that will trigger page events. As long as the event isn't activated, nothing special happens, but let's make the event active and see what happens:"));
    border.setActive(true);
    document.add(new Paragraph("This paragraph now has a background. Isn't that fantastic? By changing the event, we can even draw a border, change the line width of the border and many other things. Now let's deactivate the event."));
    border.setActive(false);
    document.add(new Paragraph("This paragraph no longer has a background."));
    document.close();
}
 
Example 29
Source Project: spotbugs   Source File: ExpandWar.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Expand the specified input stream into the specified directory, creating
 * a file named from the specified relative path.
 *
 * @param input
 *            InputStream to be copied
 * @param docBase
 *            Document base directory into which we are expanding
 * @param name
 *            Relative pathname of the file to be created
 *
 * @exception IOException
 *                if an input/output error occurs
 */
protected static void expand(InputStream input, File docBase, String name) throws IOException {

    File file = new File(docBase, name);
    // TODO: generate an OS warning for the output stream
    BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file));
    byte buffer[] = new byte[2048];
    while (true) {
        int n = input.read(buffer);
        if (n <= 0)
            break;
        output.write(buffer, 0, n);
    }
    output.close();

}
 
Example 30
Source Project: jpexs-decompiler   Source File: Test.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    PDFJob job=new PDFJob(new FileOutputStream("test.pdf"));   
    PageFormat pf=new PageFormat();
    pf.setOrientation(PageFormat.PORTRAIT);
    Paper p = new Paper();
    p.setSize(210,297); //A4
    pf.setPaper(p);
    
    BufferedImage img = ImageIO.read(new File("earth.jpg"));
    
    int w = 200;
    
    for(int i=0;i<10;i++){
        Graphics g = job.getGraphics();
        g.drawImage(img, 0, 0,w,w, null);
        g.dispose();
    }
    
    job.end();
}