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

The following examples show how to use java.io.FileOutputStream#close() . 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 check out the related API usage on the sidebar.
Example 1
/**
 * Write a file to internal storage.  Used to set up our dummy "cloud server".
 *
 * @param resId     the resource ID of the file to write to internal storage
 * @param extension the file extension (ex. .png, .mp3)
 */
private void writeFileToInternalStorage(int resId, String extension) {
    InputStream ins = getContext().getResources().openRawResource(resId);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    int size;
    byte[] buffer = new byte[1024];
    try {
        while ((size = ins.read(buffer, 0, 1024)) >= 0) {
            outputStream.write(buffer, 0, size);
        }
        ins.close();
        buffer = outputStream.toByteArray();
        String filename = getContext().getResources().getResourceEntryName(resId) + extension;
        FileOutputStream fos = getContext().openFileOutput(filename, Context.MODE_PRIVATE);
        fos.write(buffer);
        fos.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 2
Source Project: carbon-identity   File: BPELDeployer.java    License: Apache License 2.0 6 votes vote down vote up
private void removePlaceHolders(String relativeFilePath, String destination) throws IOException {

        InputStream inputStream = getClass().getResourceAsStream(CLASSPATH_SEPARATOR + relativeFilePath);
        String content = IOUtils.toString(inputStream);
        for (Map.Entry<String, String> placeHolderEntry : getPlaceHolderValues().entrySet()) {
            content = content.replaceAll(Pattern.quote(placeHolderEntry.getKey()), Matcher.quoteReplacement
                    (placeHolderEntry.getValue()));
        }
        File destinationParent = new File(destination).getParentFile();
        if (!destinationParent.exists()) {
            destinationParent.mkdirs();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(new File(destination), false);
        IOUtils.write(content, fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
        inputStream.close();
    }
 
Example 3
public static void test(Object a) {
    try {
        File objectbin = new File("object.bin");
        FileOutputStream fos = new FileOutputStream(objectbin);
        ObjectOutputStream out = new ObjectOutputStream(fos);
        out.writeObject(a);
        fos.close();
        FileInputStream fis = new FileInputStream(objectbin);
        ObjectInputStream in = new ObjectInputStream(fis);
        Object o = in.readObject();
        fis.close();
        System.err.println(o);
    } catch (Throwable ex) {
        ex.printStackTrace();
        failed = true;
    }
}
 
Example 4
public void writeParsingTables(File dir, String output_file_name) throws IOException
{
	FileOutputStream out = new FileOutputStream(new File(dir, output_file_name + SERIALIZED_PARSER_TABLES_FILE_EXT));
	try
	{
		serializeParsingTables(tables, rule_descr, grammar.error).writeTo(out);
	}
	finally
	{
		out.close();
	}
}
 
Example 5
Source Project: code   File: MavenWrapperDownloader.java    License: Apache License 2.0 5 votes vote down vote up
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
    URL website = new URL(urlString);
    ReadableByteChannel rbc;
    rbc = Channels.newChannel(website.openStream());
    FileOutputStream fos = new FileOutputStream(destination);
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    fos.close();
    rbc.close();
}
 
Example 6
private void cacheFavicon(Bitmap icon) {
	String hash = String.valueOf(Utils.getDomainName(getUrl()).hashCode());
	Log.d(Constants.TAG, "Caching icon for " + Utils.getDomainName(getUrl()));
	File image = new File(mActivity.getCacheDir(), hash + ".png");
	try {
		FileOutputStream fos = new FileOutputStream(image);
		icon.compress(Bitmap.CompressFormat.PNG, 100, fos);
		fos.flush();
		fos.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 7
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
    URL website = new URL(urlString);
    ReadableByteChannel rbc;
    rbc = Channels.newChannel(website.openStream());
    FileOutputStream fos = new FileOutputStream(destination);
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    fos.close();
    rbc.close();
}
 
Example 8
Source Project: netbeans   File: TestUtilities.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Copies a string to a specified file.
 *
 * @param f the file to use.
 * @param content the contents of the returned file.
 * @return the created file
 */
public final static File copyStringToFile (File f, String content) throws Exception {
    FileOutputStream os = new FileOutputStream(f);
    InputStream is = new ByteArrayInputStream(content.getBytes("UTF-8"));
    FileUtil.copy(is, os);
    os.close ();
    is.close();
        
    return f;
}
 
Example 9
Source Project: journaldev   File: DownloadFileFromURL.java    License: MIT License 5 votes vote down vote up
private static void downloadUsingNIO(String urlStr, String file) throws IOException {
    URL url = new URL(urlStr);
    ReadableByteChannel rbc = Channels.newChannel(url.openStream());
    FileOutputStream fos = new FileOutputStream(file);
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    fos.close();
    rbc.close();
}
 
Example 10
public void saveCustomIcon(String appComponent, String iconComponent) {
	File customIconFile = MyCache.getCustomIconFile(this, appComponent);
	Bitmap customBitmap = LauncherApp.getInstance().getIconPackManager().getBitmap(iconComponent);
	if (customIconFile != null) {
		try {
			// save icon in cache
			FileOutputStream out = new FileOutputStream(customIconFile);
			customBitmap.compress(CompressFormat.PNG, 100, out);
			out.close();
		} catch (Exception e) {
			customIconFile.delete();
		}
	}
}
 
Example 11
Source Project: reader   File: LocalFilesystem.java    License: MIT License 5 votes vote down vote up
@Override
public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
		int offset, boolean isBinary) throws IOException, NoModificationAllowedException {

       boolean append = false;
       if (offset > 0) {
           this.truncateFileAtURL(inputURL, offset);
           append = true;
       }

       byte[] rawData;
       if (isBinary) {
           rawData = Base64.decode(data, Base64.DEFAULT);
       } else {
           rawData = data.getBytes();
       }
       ByteArrayInputStream in = new ByteArrayInputStream(rawData);
       try
       {
       	byte buff[] = new byte[rawData.length];
           FileOutputStream out = new FileOutputStream(this.filesystemPathForURL(inputURL), append);
           try {
           	in.read(buff, 0, buff.length);
           	out.write(buff, 0, rawData.length);
           	out.flush();
           } finally {
           	// Always close the output
           	out.close();
           }
           broadcastNewFile(inputURL);
       }
       catch (NullPointerException e)
       {
           // This is a bug in the Android implementation of the Java Stack
           NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
           throw realException;
       }

       return rawData.length;
}
 
Example 12
Source Project: Stringlate   File: ZipUtils.java    License: MIT License 5 votes vote down vote up
public static boolean unzip(final InputStream input, final File destRootFolder,
                            final boolean flatten, final Callback.a1<Float> progressCallback,
                            final float knownLength) throws IOException {
    String filename;
    final ZipInputStream in = new ZipInputStream(new BufferedInputStream(input));

    int count;
    int written = 0;
    final byte[] buffer = new byte[BUFFER_SIZE];
    float invLength = 1f / knownLength;

    ZipEntry ze;
    while ((ze = in.getNextEntry()) != null) {
        filename = ze.getName();
        if (ze.isDirectory()) {
            if (!flatten && !new File(destRootFolder, filename).mkdirs())
                return false;
        } else {
            if (flatten) {
                final int idx = filename.lastIndexOf("/");
                if (idx != -1)
                    filename = filename.substring(idx + 1);
            }

            final FileOutputStream out = new FileOutputStream(new File(destRootFolder, filename));
            while ((count = in.read(buffer)) != -1) {
                out.write(buffer, 0, count);
                if (invLength != -1f) {
                    written += count;
                    progressCallback.callback(written * invLength);
                }
            }

            out.close();
            in.closeEntry();
        }
    }
    in.close();
    return true;
}
 
Example 13
Source Project: ramus   File: Options.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static void save(final String fileName,
                         final Properties properties, final String comments) {
    try {
        final FileOutputStream f = new FileOutputStream(fileName);
        properties.store(f, comments);
        f.close();
    } catch (final Exception e) {
        System.out.println(e.getStackTrace());
    }
}
 
Example 14
public static File makeClassList(String testCaseName, String classes[])
    throws Exception {

    File classList = getTestArtifact(testCaseName + "test.classlist", false);
    FileOutputStream fos = new FileOutputStream(classList);
    PrintStream ps = new PrintStream(fos);

    addToClassList(ps, classes);

    ps.close();
    fos.close();

    return classList;
}
 
Example 15
Source Project: rcloneExplorer   File: Log2File.java    License: MIT License 5 votes vote down vote up
@Override
protected Void doInBackground(Void... voids) {
    try {
        FileOutputStream stream = new FileOutputStream(logFile, true);
        stream.write(logMessage.getBytes());
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 16
Source Project: hbase   File: ClassLoaderTestHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add a list of jar files to another jar file under a specific folder.
 * It is used to generated coprocessor jar files which can be loaded by
 * the coprocessor class loader.  It is for testing usage only so we
 * don't be so careful about stream closing in case any exception.
 *
 * @param targetJar the target jar file
 * @param libPrefix the folder where to put inner jar files
 * @param srcJars the source inner jar files to be added
 * @throws Exception if anything doesn't work as expected
 */
public static void addJarFilesToJar(File targetJar,
    String libPrefix, File... srcJars) throws Exception {
  FileOutputStream stream = new FileOutputStream(targetJar);
  JarOutputStream out = new JarOutputStream(stream, new Manifest());
  byte[] buffer = new byte[BUFFER_SIZE];

  for (File jarFile: srcJars) {
    // Add archive entry
    JarEntry jarAdd = new JarEntry(libPrefix + jarFile.getName());
    jarAdd.setTime(jarFile.lastModified());
    out.putNextEntry(jarAdd);

    // Write file to archive
    FileInputStream in = new FileInputStream(jarFile);
    while (true) {
      int nRead = in.read(buffer, 0, buffer.length);
      if (nRead <= 0) {
        break;
      }

      out.write(buffer, 0, nRead);
    }
    in.close();
  }
  out.close();
  stream.close();
  LOG.info("Adding jar file to outer jar file completed");
}
 
Example 17
Source Project: bamboobsc   File: KpiReportExcelCommand.java    License: Apache License 2.0 4 votes vote down vote up
private String createExcel(Context context) throws Exception {
	String visionOid = (String)context.get("visionOid");
	VisionVO vision = null;
	BscStructTreeObj treeObj = (BscStructTreeObj)this.getResult(context);
	for (VisionVO visionObj : treeObj.getVisions()) {
		if (visionObj.getOid().equals(visionOid)) {
			vision = visionObj;
		}
	}
	BscReportPropertyUtils.loadData();
	BscReportSupportUtils.loadExpression(); // 2015-04-18 add
	String fileName = SimpleUtils.getUUIDStr() + ".xlsx";
	String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName;	
	int row = 24;
	if (context.get("pieCanvasToData") == null || context.get("barCanvasToData") == null) {
		row = 0;
	}
	XSSFWorkbook wb = new XSSFWorkbook();				
	XSSFSheet sh = wb.createSheet();
	
	row += this.createHead(wb, sh, row, vision);
	row = this.createMainBody(wb, sh, row, vision);
	
	row = row + 1; // 空一列
	row = this.createDateRange(wb, sh, row, vision, context);
	if (context.get("pieCanvasToData") != null && context.get("barCanvasToData") != null) {
		this.putCharts(wb, sh, context);
	}
	this.putSignature(wb, sh, row+1, context);
	
       FileOutputStream out = new FileOutputStream(fileFullPath);
       wb.write(out);
       out.close();
       wb = null;
       
       File file = new File(fileFullPath);
	String oid = UploadSupportUtils.create(
			Constants.getSystem(), UploadTypes.IS_TEMP, false, file, "kpi-report.xlsx");
	file = null;
	return oid;
}
 
Example 18
Source Project: big-c   File: TestContainerLaunch.java    License: Apache License 2.0 4 votes vote down vote up
@Test (timeout = 20000)
public void testContainerLaunchStdoutAndStderrDiagnostics() throws IOException {

  File shellFile = null;
  try {
    shellFile = Shell.appendScriptExtension(tmpDir, "hello");
    // echo "hello" to stdout and "error" to stderr and exit code with 2;
    String command = Shell.WINDOWS ?
        "@echo \"hello\" & @echo \"error\" 1>&2 & exit /b 2" :
        "echo \"hello\"; echo \"error\" 1>&2; exit 2;";
    PrintWriter writer = new PrintWriter(new FileOutputStream(shellFile));
    FileUtil.setExecutable(shellFile, true);
    writer.println(command);
    writer.close();
    Map<Path, List<String>> resources =
        new HashMap<Path, List<String>>();
    FileOutputStream fos = new FileOutputStream(shellFile, true);

    Map<String, String> env = new HashMap<String, String>();
    List<String> commands = new ArrayList<String>();
    commands.add(command);
    ContainerExecutor exec = new DefaultContainerExecutor();
    exec.writeLaunchEnv(fos, env, resources, commands);
    fos.flush();
    fos.close();

    Shell.ShellCommandExecutor shexc
    = new Shell.ShellCommandExecutor(new String[]{shellFile.getAbsolutePath()}, tmpDir);
    String diagnostics = null;
    try {
      shexc.execute();
      Assert.fail("Should catch exception");
    } catch(ExitCodeException e){
      diagnostics = e.getMessage();
    }
    // test stderr
    Assert.assertTrue(diagnostics.contains("error"));
    // test stdout
    Assert.assertTrue(shexc.getOutput().contains("hello"));
    Assert.assertTrue(shexc.getExitCode() == 2);
  }
  finally {
    // cleanup
    if (shellFile != null
        && shellFile.exists()) {
      shellFile.delete();
    }
  }
}
 
Example 19
@Override
protected Boolean doInBackground(View... views) {
    final View poem = views[0];
    boolean result = false;

    if (App.isExternalStorageWritable()) {
        // generating image
        final Bitmap bitmap = Bitmap.createBitmap(
                getResources().getDimensionPixelSize(R.dimen.share_width_px),
                getResources().getDimensionPixelSize(R.dimen.share_height_px),
                Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        poem.draw(canvas);

        final File picFile = App.getPoemFile("poem_" + poem.getTag() + ".jpg");

        try {
            picFile.createNewFile();
            final FileOutputStream picOut = new FileOutputStream(picFile);
            final boolean saved = bitmap.compress(Bitmap.CompressFormat.JPEG, 90, picOut);
            if (saved) {
                final CharSequence hashtag
                        = ((TextView) poem.findViewById(R.id.poem_theme)).getText();

                // create Uri from local image file://<absolute path>
                final Uri imageUri = Uri.fromFile(picFile);
                final TweetComposer.Builder builder
                        = new TweetComposer.Builder(PoemHistoryActivity.this)
                        .text(getApplicationContext().getResources()
                                .getString(R.string.share_poem_tweet_text) + " " + hashtag)
                        .image(imageUri);
                builder.show();

                result = true;
            } else {
                Crashlytics.log(Log.ERROR, TAG, "Error when trying to save Bitmap of poem");
                Toast.makeText(getApplicationContext(),
                        getResources().getString(R.string.toast_share_error),
                        Toast.LENGTH_SHORT).show();
            }
            picOut.close();
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(),
                    getResources().getString(R.string.toast_share_error),
                    Toast.LENGTH_SHORT).show();
            Crashlytics.logException(e);
            e.printStackTrace();
        }

        poem.destroyDrawingCache();
    } else {
        Toast.makeText(getApplicationContext(),
                getResources().getString(R.string.toast_share_error),
                Toast.LENGTH_SHORT).show();
        Crashlytics.log(Log.ERROR, TAG, "External Storage not writable");
    }

    return result;
}
 
Example 20
@Test
public void testGetKeystoreWithNoClientAuth() throws Exception{

	// jks format
	byte[] dummyTruststore = Base64.decode(SecureGetTest.TEST_TS1);
	byte[] dummyKeystore = Base64.decode(SecureGetTest.TEST_KS1);

	File tempKeystore = File.createTempFile(this.getClass().getName(), ".keystore");
	File tempTruststore = File.createTempFile(this.getClass().getName(), ".truststore");

	FileOutputStream keystoreFileOut = new FileOutputStream(tempKeystore);
       try {
           keystoreFileOut.write(dummyKeystore);
       } finally {
           keystoreFileOut.close();
       }

	FileOutputStream truststoreFileOut = new FileOutputStream(tempTruststore);
       try {
           truststoreFileOut.write(dummyTruststore);
       } finally {
           truststoreFileOut.close();
       }

	AbstractConfiguration cm = ConfigurationManager.getConfigInstance();

	String name = this.getClass().getName() + ".test2";

	String configPrefix = name + "." + "ribbon";

	cm.setProperty(configPrefix + "." +  CommonClientConfigKey.IsSecure, "true");
	cm.setProperty(configPrefix + "." +  CommonClientConfigKey.KeyStore, tempKeystore.getAbsolutePath());
	cm.setProperty(configPrefix + "." +  CommonClientConfigKey.KeyStorePassword, "changeit");

	RestClient client = (RestClient) ClientFactory.getNamedClient(name);

	KeyStore keyStore = client.getKeyStore();

	Certificate cert = keyStore.getCertificate("ribbon_key");

	assertNotNull(cert);
}