java.io.FileOutputStream Java Examples

The following examples show how to use java.io.FileOutputStream. 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: Logger.java    From android-wear-gopro-remote with 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 #2
Source File: NativeLibraryLoader.java    From lavaplayer with 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 #3
Source File: Options.java    From cordova-plugin-firebase-extended-notification with MIT License 6 votes vote down vote up
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 #4
Source File: MyRenderer.java    From Viewer with 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 #5
Source File: ZipUtils.java    From teiid-spring-boot with 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 #6
Source File: CrossRealm.java    From jdk8u60 with 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 #7
Source File: PackagedProgramTest.java    From flink with 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 File: ConsoleDecompiler.java    From JByteMod-Beta with GNU General Public License v2.0 6 votes vote down vote up
@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 #9
Source File: FileBackupStore.java    From presto with 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 #10
Source File: NewModelByteBufferFile.java    From TencentKona-8 with 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 #11
Source File: TestLocal2.java    From spork with 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 #12
Source File: DebianPackageWriter.java    From neoscada with 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 #13
Source File: ASSERT.java    From OpenEphyra with 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 #14
Source File: SplitterProcessorIntegrationTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@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 #15
Source File: SaveAttachmentTask.java    From Silence with 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 #16
Source File: TestLibrary.java    From jdk8u60 with 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 #17
Source File: MigrateForm.java    From jeewx with 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 #18
Source File: Read.java    From hottub with 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 #19
Source File: WebViewJavascriptInterfaceActivity.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #20
Source File: ThumbnailGenerator.java    From sling-samples with 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 #21
Source File: VKUploadImage.java    From cordova-social-vk with 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 #22
Source File: Utils.java    From SmartPaperScan with 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 #23
Source File: SimpleLogger.java    From JDA with 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 #24
Source File: SettingsApiImpl.java    From sc2gears with 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 #25
Source File: SourceApiHelper.java    From HouSi with 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 #26
Source File: ColorParagraphBackground.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #27
Source File: ExpandWar.java    From spotbugs with 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 #28
Source File: Test.java    From jpexs-decompiler with 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();
}
 
Example #29
Source File: PSPrinterJob.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public Object run() {
    try {

            /* Write to a temporary file which will be spooled to
             * the printer then deleted. In the case that the file
             * is not removed for some reason, request that it is
             * removed when the VM exits.
             */
            spoolFile = Files.createTempFile("javaprint", ".ps").toFile();
            spoolFile.deleteOnExit();

        result = new FileOutputStream(spoolFile);
        return result;
    } catch (IOException ex) {
        // If there is an IOError we subvert it to a PrinterException.
        pex = new PrinterIOException(ex);
    }
    return null;
}
 
Example #30
Source File: MessageSendServerTab.java    From IGW-mod with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void fromBytes(ByteBuf buf){
    File folder = new File(IGWMod.proxy.getSaveLocation() + File.separator + "igwmod" + File.separator);

    folder.mkdirs();
    try {
        FileUtils.deleteDirectory(folder);//clear the folder
    } catch(IOException e1) {
        e1.printStackTrace();
    }
    folder.mkdirs();

    int fileAmount = buf.readInt();
    for(int i = 0; i < fileAmount; i++) {
        try {
            File file = new File(folder.getAbsolutePath() + File.separator + ByteBufUtils.readUTF8String(buf));
            byte[] fileBytes = new byte[buf.readInt()];
            buf.readBytes(fileBytes);
            FileOutputStream stream = new FileOutputStream(file);
            IOUtils.write(fileBytes, stream);
            stream.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}