Java Code Examples for java.io.FileOutputStream

The following are top voted examples for showing how to use java.io.FileOutputStream. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jdk8u-jdk   File: GetRoot.java   Source Code and License 8 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 2
Project: calcite-avatica   File: SslDriverTest.java   Source Code and License 8 votes vote down vote up
private void createSelfSignedCert(File targetKeystore, String keyName,
    String keystorePassword) {
  if (targetKeystore.exists()) {
    throw new RuntimeException("Keystore already exists: " + targetKeystore);
  }

  try {
    KeyPair kp = generateKeyPair();

    X509CertificateObject cert = generateCert(keyName, kp, true, kp.getPublic(),
        kp.getPrivate());

    char[] password = keystorePassword.toCharArray();
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(null, null);
    keystore.setCertificateEntry(keyName + "Cert", cert);
    keystore.setKeyEntry(keyName + "Key", kp.getPrivate(), password, new Certificate[] {cert});
    try (FileOutputStream fos = new FileOutputStream(targetKeystore)) {
      keystore.store(fos, password);
    }
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 3
Project: fingerblox   File: Utils.java   Source Code and License 8 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 4
Project: APITools   File: PubUtils.java   Source Code and License 7 votes vote down vote up
public static long copyFile(File f1, File f2) throws Exception {
	long time = new Date().getTime();
	int length = 2097152;
	FileInputStream in = new FileInputStream(f1);
	FileOutputStream out = new FileOutputStream(f2);
	byte[] buffer = new byte[length];
	while (true) {
		int ins = in.read(buffer);
		if (ins == -1) {
			in.close();
			out.flush();
			out.close();
			return new Date().getTime() - time;
		} else
			out.write(buffer, 0, ins);
	}
}
 
Example 5
Project: BibliotecaPS   File: BlobTest.java   Source Code and License 6 votes vote down vote up
private void createBlobFile(int size) throws Exception {
    if (testBlobFile != null && testBlobFile.length() != size) {
        testBlobFile.delete();
    }

    testBlobFile = File.createTempFile(TEST_BLOB_FILE_PREFIX, ".dat");
    testBlobFile.deleteOnExit();

    // TODO: following cleanup doesn't work correctly during concurrent execution of testsuite 
    // cleanupTempFiles(testBlobFile, TEST_BLOB_FILE_PREFIX);

    BufferedOutputStream bOut = new BufferedOutputStream(new FileOutputStream(testBlobFile));

    int dataRange = Byte.MAX_VALUE - Byte.MIN_VALUE;

    for (int i = 0; i < size; i++) {
        bOut.write((byte) ((Math.random() * dataRange) + Byte.MIN_VALUE));
    }

    bOut.flush();
    bOut.close();
}
 
Example 6
Project: ImageLoaderSupportGif   File: HomeActivity.java   Source Code and License 6 votes vote down vote up
private void copyTestImageToSdCard(final File testImageOnSdCard) {
	new Thread(new Runnable() {
		@Override
		public void run() {
			try {
				InputStream is = getAssets().open(TEST_FILE_NAME);
				FileOutputStream fos = new FileOutputStream(testImageOnSdCard);
				byte[] buffer = new byte[8192];
				int read;
				try {
					while ((read = is.read(buffer)) != -1) {
						fos.write(buffer, 0, read);
					}
				} finally {
					fos.flush();
					fos.close();
					is.close();
				}
			} catch (IOException e) {
				L.w("Can't copy test image onto SD card");
			}
		}
	}).start();
}
 
Example 7
Project: SER316-Ingolstadt   File: FileStorage.java   Source Code and License 6 votes vote down vote up
public static void saveDocument(Document doc, String filePath) {
    /**
     * @todo: Configurable parameters
     */
    try {
        /*The XOM bug: reserved characters are not escaped*/
        //Serializer serializer = new Serializer(new FileOutputStream(filePath), "UTF-8");
        //serializer.write(doc);
        OutputStreamWriter fw =
            new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8");
        fw.write(doc.toXML());
        fw.flush();
        fw.close();
    }
    catch (IOException ex) {
        new ExceptionDialog(
            ex,
            "Failed to write a document to " + filePath,
            "");
    }
}
 
Example 8
Project: boohee_v5.6   File: DiskBasedCache.java   Source Code and License 6 votes vote down vote up
public synchronized void put(String key, Entry entry) {
    pruneIfNeeded(entry.data.length);
    File file = getFileForKey(key);
    try {
        BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file));
        CacheHeader e = new CacheHeader(key, entry);
        if (e.writeHeader(fos)) {
            fos.write(entry.data);
            fos.close();
            putEntry(key, e);
        } else {
            fos.close();
            VolleyLog.d("Failed to write header for %s", file.getAbsolutePath());
            throw new IOException();
        }
    } catch (IOException e2) {
        if (!file.delete()) {
            VolleyLog.d("Could not clean up file %s", file.getAbsolutePath());
        }
    }
}
 
Example 9
Project: openjdk-jdk10   File: B7050028.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
    int len = conn.getContentLength();
    byte[] data = new byte[len];
    InputStream is = conn.getInputStream();
    is.read(data);
    is.close();
    conn.setDefaultUseCaches(false);
    File jar = File.createTempFile("B7050028", ".jar");
    jar.deleteOnExit();
    OutputStream os = new FileOutputStream(jar);
    ZipOutputStream zos = new ZipOutputStream(os);
    ZipEntry ze = new ZipEntry("B7050028.class");
    ze.setMethod(ZipEntry.STORED);
    ze.setSize(len);
    CRC32 crc = new CRC32();
    crc.update(data);
    ze.setCrc(crc.getValue());
    zos.putNextEntry(ze);
    zos.write(data, 0, len);
    zos.closeEntry();
    zos.finish();
    zos.close();
    os.close();
    System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
 
Example 10
Project: EnchantedFortress   File: HighScores.java   Source Code and License 6 votes vote down vote up
private void save(Context context) {
    byte[] byteBuffer = new byte[Double.SIZE / Byte.SIZE];

    try {
        FileOutputStream stream = context.openFileOutput(ScoresFileName, Context.MODE_PRIVATE);

        ByteBuffer.wrap(byteBuffer).putDouble(BuildConfig.VERSION_CODE);
        stream.write(byteBuffer);

        for (Map.Entry<Integer, List<ScoreEntry>> group : this.scores.entrySet()) {
            stream.write(group.getKey());
            stream.write(group.getValue().size());

            for (ScoreEntry score : group.getValue()) {
                double[] data = score.saveData();

                for (double val : data) {
                    ByteBuffer.wrap(byteBuffer).putDouble(val);
                    stream.write(byteBuffer);
                }
            }
        }

        stream.close();
        Log.i("HighScores", "Saved");
    } catch (Exception e) {
        Log.e("HighScores", "Autosave failed", e);
    }
}
 
Example 11
Project: chromium-net-for-android   File: UploadDataProvidersTest.java   Source Code and License 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    mOldVmPolicy = StrictMode.getVmPolicy();
    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                                   .detectLeakedClosableObjects()
                                   .penaltyLog()
                                   .penaltyDeath()
                                   .build());
    mTestFramework = startCronetTestFramework();
    assertTrue(NativeTestServer.startNativeTestServer(getContext()));
    // Add url interceptors after native application context is initialized.
    MockUrlRequestJobFactory.setUp();
    mFile = new File(getContext().getCacheDir().getPath() + "/tmpfile");
    FileOutputStream fileOutputStream = new FileOutputStream(mFile);
    try {
        fileOutputStream.write(LOREM.getBytes("UTF-8"));
    } finally {
        fileOutputStream.close();
    }
}
 
Example 12
Project: creacoinj   File: BuildCheckpoints.java   Source Code and License 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 13
Project: Allshare   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    momentCheckBox = (CheckBox) findViewById(R.id.shareToMomentCheckBox);
    qzoneCheckBox = (CheckBox) findViewById(R.id.shareToQzoneCheckBox);

    icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
    if (!ICON_FILE.exists()) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(ICON_FILE);
            icon.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example 14
Project: android-project-gallery   File: RangeFileAsyncHttpResponseHandler.java   Source Code and License 6 votes vote down vote up
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        long contentLength = entity.getContentLength() + current;
        FileOutputStream buffer = new FileOutputStream(getTargetFile(), append);
        if (instream != null) {
            try {
                byte[] tmp = new byte[BUFFER_SIZE];
                int l;
                while (current < contentLength && (l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                    current += l;
                    buffer.write(tmp, 0, l);
                    sendProgressMessage((int) current, (int) contentLength);
                }
            } finally {
                instream.close();
                buffer.flush();
                buffer.close();
            }
        }
    }
    return null;
}
 
Example 15
Project: Selector   File: ImageCacheUtils.java   Source Code and License 6 votes vote down vote up
public static String saveToSDCard(byte[] data,Context context,String path) throws IOException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String filename = "IMG_" + format.format(date) + ".jpg";
        File fileFolder = new File(path);
        if (!fileFolder.exists()) {
            fileFolder.mkdirs();
        }
        File jpgFile = new File(fileFolder, filename);
        FileOutputStream outputStream = new FileOutputStream(jpgFile); //
        //刷新相册
        MediaScannerConnection.scanFile(context,
                new String[]{jpgFile.getAbsolutePath()}, null, null);

        outputStream.write(data);
        outputStream.close();
//        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//        Uri uri = Uri.fromFile(new File(Environment
//                .getExternalStorageDirectory() + "/DeepbayPicture/" + filename));
//        intent.setData(uri);
//        mContext.sendBroadcast(intent);
        return jpgFile.getAbsolutePath();
    }
 
Example 16
Project: Tarski   File: MiniSatExternal.java   Source Code and License 6 votes vote down vote up
private void finalizeCnf() {
    try {
        free();
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(cnfFile));
        File tmp = new File(cnfFile + ".tmp"); 
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tmp)); 
        byte[] header = String.format("p cnf %s %s\n", vars, clauses).getBytes();
        out.write(header);
        int ch;
        while ((ch = in.read()) != -1) {
            out.write(ch);
        }
        in.close();
        out.close();
        tmp.renameTo(cnfFile);
    } catch (IOException e) {
        throw new RuntimeException("could not preprend header to cnf file: " + cnfFile.getAbsolutePath(), e);
    }
}
 
Example 17
Project: hadoop   File: TestSharedFileDescriptorFactory.java   Source Code and License 6 votes vote down vote up
@Test(timeout=10000)
public void testReadAndWrite() throws Exception {
  File path = new File(TEST_BASE, "testReadAndWrite");
  path.mkdirs();
  SharedFileDescriptorFactory factory =
      SharedFileDescriptorFactory.create("woot_",
          new String[] { path.getAbsolutePath() });
  FileInputStream inStream =
      factory.createDescriptor("testReadAndWrite", 4096);
  FileOutputStream outStream = new FileOutputStream(inStream.getFD());
  outStream.write(101);
  inStream.getChannel().position(0);
  Assert.assertEquals(101, inStream.read());
  inStream.close();
  outStream.close();
  FileUtil.fullyDelete(path);
}
 
Example 18
Project: JavaGraph   File: SaveAction.java   Source Code and License 6 votes vote down vote up
/**
 * Saves the text under a given name as a file outside the grammar.
 * @return {@code true} if the text was saved within the grammar
 */
public boolean doSaveTextAs(QualName name, String text) {
    boolean result = false;
    File selectedFile = askSaveResource(name);
    // now save, if so required
    if (selectedFile != null) {
        try {
            QualName nameInGrammar = getNameInGrammar(selectedFile);
            if (nameInGrammar == null) {
                // store as external file
                try (FileOutputStream out = new FileOutputStream(selectedFile)) {
                    TextBasedModel.store(text, out);
                }
            } else {
                // store in grammar
                result = doSaveText(nameInGrammar, text);
            }
        } catch (IOException exc) {
            showErrorDialog(exc,
                "Error while writing %s to '%s'",
                getResourceKind().getDescription(),
                selectedFile);
        }
    }
    return result;
}
 
Example 19
Project: GravityBox   File: KeyguardImageService.java   Source Code and License 6 votes vote down vote up
private boolean saveImage() {
    try {
        Bitmap tmpBmp = BitmapFactory.decodeStream(
                new ByteArrayInputStream(mOutputStream.toByteArray()));
        if (tmpBmp != null) {
            if (mPrefs.getBoolean(GravityBoxSettings.PREF_KEY_LOCKSCREEN_BACKGROUND_BLUR_EFFECT, false)) {
                tmpBmp = Utils.blurBitmap(this, tmpBmp, mPrefs.getInt(
                        GravityBoxSettings.PREF_KEY_LOCKSCREEN_BACKGROUND_BLUR_INTENSITY, 14));
            }
            tmpBmp.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(mKisImageFile));
            mKisImageFile.setReadable(true, false);
            tmpBmp.recycle();
            return true;
        }
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 20
Project: JInsight   File: RuleScriptGenerator.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException {
  File outputFile = new File(args[0]);
  List<String> helpers = new ArrayList<>(args.length);
  for (int i = 1; i < args.length; i++) {
    String helper = args[i].replaceAll("\\.class$", "")
        .replaceAll("\\\\", ".")
        .replaceAll("/", ".")
        .replaceAll("^\\.", "");
    helpers.add(helper);
  }
  //System.out.println(outputFile);
  //System.out.println(helpers);
  FileOutputStream fileOutputStream = new FileOutputStream(outputFile, true);
  PrintStream ps = new PrintStream(new BufferedOutputStream(fileOutputStream), false, "UTF-8");
  new RuleScriptGenerator(helpers).generateRules(ps);
  ps.flush();
  ps.close();
}
 
Example 21
Project: boqa   File: WordNetParserTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testWordnetParser() throws IOException
{
    TermContainer tc = WordNetParser.parserWordnet("WordNet-3.0/dict/data.noun");
    Ontology ontology = new Ontology(tc);

    Set<TermID> ts = new HashSet<TermID>();
    // ts.addAll(ontology.getTermsOfInducedGraph(null, ontology.getTerm("WNO:09571693").getID())); /* Orion */
    // ts.addAll(ontology.getTermsOfInducedGraph(null, ontology.getTerm("WNO:09380117").getID())); /* Orion */
    ts.addAll(ontology.getTermsOfInducedGraph(null, ontology.getTerm("WNO:09917593").getID())); /* Child */
    ts.addAll(ontology.getTermsOfInducedGraph(null, ontology.getTerm("WNO:05560787").getID())); /* Leg */

    ontology.getGraph().writeDOT(new FileOutputStream(new File("test.dot")),
        ontology.getSetOfTermsFromSetOfTermIds(ts), new DotAttributesProvider<Term>()
        {
            @Override
            public String getDotNodeAttributes(Term vt)
            {
                return "label=\"" + vt.getName() + "\"";
            }
        });
}
 
Example 22
Project: AndroidDBForData   File: IOHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Compress by quality,  and generate image to the path specified
 *
 * @param image
 * @param outPath
 * @param maxSize target will be compressed to be smaller than this size.(kb)
 * @throws IOException
 */
public static void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    // scale
    int options = 100;
    // Store the bitmap into output stream(no compress)
    image.compress(Bitmap.CompressFormat.JPEG, options, os);
    // Compress by loop
    while ( os.toByteArray().length / 1024 > maxSize) {
        // Clean up os
        os.reset();
        // interval 10
        options -= 10;
        image.compress(Bitmap.CompressFormat.JPEG, options, os);
    }

    // Generate compressed image file
    FileOutputStream fos = new FileOutputStream(outPath);
    fos.write(os.toByteArray());
    fos.flush();
    fos.close();
}
 
Example 23
Project: MetadataEditor   File: FlacInfoReader.java   Source Code and License 6 votes vote down vote up
/**
 * Count the number of metadatablocks, useful for debugging
 *
 * @param f
 * @return
 * @throws CannotReadException
 * @throws IOException
 */
public int countMetaBlocks(File f) throws CannotReadException, IOException {
    FileChannel fc = new FileOutputStream(f.getAbsolutePath(), false).getChannel();
    FlacStreamReader flacStream = new FlacStreamReader(fc, f.getAbsolutePath() + " ");
    flacStream.findStream();

    boolean isLastBlock = false;

    int count = 0;
    while (!isLastBlock) {
        MetadataBlockHeader mbh = MetadataBlockHeader.readHeader(fc);
        logger.config(f + ":Found block:" + mbh.getBlockType());
        fc.position(fc.position() + mbh.getDataLength());
        isLastBlock = mbh.isLastBlock();
        count++;
    }
    return count;
}
 
Example 24
Project: CoolClock   File: FileUtils.java   Source Code and License 6 votes vote down vote up
public static void writeObject(String key, Object obj) {
    if (obj == null || key == null) {
        return;

    }
    try {
        FileOutputStream out = new FileOutputStream(getFile(key));
        ObjectOutputStream outObj = new ObjectOutputStream(out);
        outObj.writeObject(obj);
        outObj.flush();
        outObj.close();
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 25
Project: CDN-FX-2.2   File: XMLUpdater.java   Source Code and License 6 votes vote down vote up
public boolean update(){
    try{
        DebugLogger.log("Updating XML...", Level.INFO);
        String path = Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
        path = path.substring(1, path.lastIndexOf("/")) + "/";
        ReadableByteChannel in = Channels.newChannel(new URL(updateURL + "community.xml").openStream());
        FileChannel out = new FileOutputStream((path+"community.xml")).getChannel();

        out.transferFrom(in, 0, Long.MAX_VALUE);
        in.close();
        out.close();

        DebugLogger.log("XML Update successful!", Level.INFO);
        return true;

    }catch(Exception e){
        DebugLogger.log("XML Update failed!", Level.INFO);
        return false;
    }
}
 
Example 26
Project: Reer   File: LocalDirectoryBuildCache.java   Source Code and License 6 votes vote down vote up
@Override
public void store(final BuildCacheKey key, final BuildCacheEntryWriter result) throws BuildCacheException {
    persistentCache.useCache("store build cache entry", new Runnable() {
        @Override
        public void run() {
            File file = getFile(key.getHashCode());
            try {
                Closer closer = Closer.create();
                OutputStream output = closer.register(new FileOutputStream(file));
                try {
                    result.writeTo(output);
                } finally {
                    closer.close();
                }
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
        }
    });
}
 
Example 27
Project: Nird2   File: FilePlugin.java   Source Code and License 6 votes vote down vote up
@Nullable
private TransportConnectionWriter createWriter(String filename) {
	if (!running) return null;
	File dir = chooseOutputDirectory();
	if (dir == null || !dir.exists() || !dir.isDirectory()) return null;
	File f = new File(dir, filename);
	try {
		long capacity = dir.getFreeSpace();
		if (capacity < MIN_STREAM_LENGTH) return null;
		OutputStream out = new FileOutputStream(f);
		return new FileTransportWriter(f, out, capacity, this);
	} catch (IOException e) {
		if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
		f.delete();
		return null;
	}
}
 
Example 28
Project: sAINT   File: sAINT.java   Source Code and License 6 votes vote down vote up
public static void copyFolder(File src, File dest) throws IOException {
    if (src.isDirectory()) {
        if (!dest.exists()) {
            dest.mkdir();
        }
        String files[] = src.list();
        for (String file : files) {
            File srcFile = new File(src, file);
            File destFile = new File(dest, file);
            copyFolder(srcFile, destFile);
        }
    } else {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dest);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }

        in.close();
        out.close();
    }
}
 
Example 29
Project: Cubeland   File: SavingSystem.java   Source Code and License 6 votes vote down vote up
private void saveMetaData(String saveName) {
	try {
		// open file
		File file = new File(savePath + saveName + "/meta.data");
		file.getParentFile().mkdirs();
		file.createNewFile();
		DataOutputStream out = new DataOutputStream(new FileOutputStream(file));

		out.write(SAVE_VERSION_META);

		// save data
		out.writeUTF(scene.envStates.levelName);

		out.close();
	} catch (IOException e1) {
		Logger.error("Meta could not be saved!");
	}
}
 
Example 30
Project: SparkSeq   File: AdaptiveHuffmanCompress.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    // Handle command line arguments
    if (args.length != 2) {
        System.err.println("Usage: java AdaptiveHuffmanCompress InputFile OutputFile");
        System.exit(1);
        return;
    }
    File inputFile = new File(args[0]);
    File outputFile = new File(args[1]);

    // Perform file compression
    InputStream in = new BufferedInputStream(new FileInputStream(inputFile));
    BitOutputStream out = new BitOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
    try {
        compress(in, out);
    } finally {
        out.close();
        in.close();
    }
}
 
Example 31
Project: Hotspot-master-devp   File: BitmapCommonUtils.java   Source Code and License 6 votes vote down vote up
public static void saveBitmap2SdCard(Bitmap drawingCache,String filePath) {

        try {
            File file = new File(filePath);
            if(file.exists())
                file.delete();
            FileOutputStream fos = new FileOutputStream(filePath);
            drawingCache.compress(Bitmap.CompressFormat.PNG,80,fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(drawingCache!=null&&!drawingCache.isRecycled()) {
                drawingCache.recycle();
            }
        }
    }
 
Example 32
Project: mir2.core   File: WIL.java   Source Code and License 6 votes vote down vote up
private void tex8bit(int index, byte[] rgb8s, int width, int height, int offsetX, int offsetY) throws IOException {
	imageInfos[index].setColorBit((byte) bitCount);
	imageInfos[index].setWidth((short) width);
	imageInfos[index].setHeight((short) height);
	imageInfos[index].setOffsetX((short) offsetX);
	imageInfos[index].setOffsetY((short) offsetY);
	File fimg = new File(tmp_wil_dir.getAbsolutePath() + File.separator + index);
	FileOutputStream fosimg = new FileOutputStream(fimg);
	int skipBytes = SDK.skipBytes(bitCount, width);
	boolean hasBlank = rgb8s.length == SDK.widthBytes(8 * width) * height;
	for (int h = height - 1; h >= 0; --h) {
		for (int w = 0; w < width; ++w) {
			// 跳过填充字节
			if (w == 0)
				for (int i = 0; i < skipBytes; ++i)
					fosimg.write(0);
			int cindex = w + h * width;
			if (hasBlank)
				cindex += (h + 1) * SDK.widthBytes(8 * width);
			fosimg.write(rgb8s[cindex]);
		}
	}
	fosimg.close();
}
 
Example 33
Project: Ec2m   File: CamaraActivity.java   Source Code and License 5 votes vote down vote up
@Override
        public void onPictureTaken(byte[] data, Camera camera) {
            try {
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                Matrix matrix = new Matrix();
                matrix.setRotate(270);

                File jpgFile = new File(Environment.getExternalStorageDirectory() + "/DCIM/camera");
                if (!jpgFile.exists()) {
                    jpgFile.mkdir();
                }
                File jpgFile1 = new File(jpgFile.getAbsoluteFile(), System.currentTimeMillis() + ".jpg");
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                FileOutputStream fos = new FileOutputStream(jpgFile1);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
//                ToastUtils.show(getApplicationContext(), getString(R.string.save_success));
                fos.close();
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(jpgFile1);
                intent.setData(uri);
                sendBroadcast(intent);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (Build.VERSION.SDK_INT >= 24) {
                    reset();
                }
                isTakingPhoto = false;
            }
        }
 
Example 34
Project: CorePatch   File: GdiffTest.java   Source Code and License 5 votes vote down vote up
/**
 * Helper for calling patch(), expects to throw an error.
 *
 * @param inputBytes the bytes representing the input (original) file
 * @param inputLimit if -1, use entire input array.  Otherwise, shorten input to this length.
 * @param patchBytes byte array containing patch
 * @param patchLimit if -1, use entire patch array.  Otherwise, shorten patch to this length.
 * @param outputLimit if -1, expect a "very large" output.  Otherwise, set limit this length.
 */
private void checkExpectedIOException(byte[] inputBytes, int inputLimit,
    byte[] patchBytes, int patchLimit, int outputLimit) throws IOException {
  if (inputLimit == -1) {
    inputLimit = inputBytes.length;
  }
  // Create "input file".
  File inputFile = File.createTempFile("testExample", null);
  FileOutputStream writeInputFile = new FileOutputStream(inputFile);
  writeInputFile.write(inputBytes, 0, inputLimit);
  writeInputFile.close();
  RandomAccessFile readInputFile = new RandomAccessFile(inputFile, "r");

  if (patchLimit == -1) {
    patchLimit = patchBytes.length;
  }
  ByteArrayInputStream patchStream = new ByteArrayInputStream(patchBytes, 0, patchLimit);

  if (outputLimit == -1) {
    outputLimit = (inputBytes.length * 2) + (patchBytes.length * 2);    // 100% arbitrary
  }
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  try {
    Gdiff.patch(readInputFile, patchStream, outputStream, outputLimit);
    Assert.fail("Expected IOException");
  } catch (IOException expected) {
  }
  Assert.assertTrue(outputStream.size() <= outputLimit);
}
 
Example 35
Project: MobiRNN-EMDL17   File: Util.java   Source Code and License 5 votes vote down vote up
public static float[][][] getInputData(String folder) throws IOException {
    if (cachedInputs != null) {
        return cachedInputs;
    }

    final float[][][] inputs;
    final Kryo kryo = new Kryo();
    kryo.register(float[][][].class);
    final File dataBinFile = new File(getDataPath() + File.separator + "data-small.bin");
    if (dataBinFile.exists()) {
        Logger.i("begin reading input data bin: %s", dataBinFile.getAbsolutePath());
        Input input = new Input(new FileInputStream(dataBinFile));
        inputs = kryo.readObject(input, float[][][].class);
        input.close();
        Logger.i("begin reading input data bin: %s", dataBinFile.getAbsolutePath());
    } else {
        Logger.i("begin parsing input data");
        String inputFilePath =
                folder + File.separator + "test_data" + File.separator + "sensor";
        inputs = parseInputData(inputFilePath);
        Logger.i("end parsing input data");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Output output = new Output(new FileOutputStream(dataBinFile));
                    kryo.writeObject(output, inputs);
                    output.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    cachedInputs = inputs;
    return cachedInputs;
}
 
Example 36
Project: Dahlem_SER316   File: Configuration.java   Source Code and License 5 votes vote down vote up
public static void saveConfig() {
  try {
  config.save(new FileOutputStream(configPath));
  }
  catch (Exception e) {
   new ExceptionDialog(e, "Failed to save a configuration file:<br>"+configPath, "");
  }
}
 
Example 37
Project: Moenagade   File: DeferredFileOutputStream.java   Source Code and License 5 votes vote down vote up
/**
 * Switches the underlying output stream from a memory based stream to one
 * that is backed by disk. This is the point at which we realise that too
 * much data is being written to keep in memory, so we elect to switch to
 * disk-based storage.
 *
 * @exception IOException if an error occurs.
 */
@Override
protected void thresholdReached() throws IOException
{
    if (prefix != null) {
        outputFile = File.createTempFile(prefix, suffix, directory);
    }
    FileOutputStream fos = new FileOutputStream(outputFile);
    memoryOutputStream.writeTo(fos);
    currentOutputStream = fos;
    memoryOutputStream = null;
}
 
Example 38
Project: apache-tomcat-7.0.73-with-comment   File: AccessLogValve.java   Source Code and License 5 votes vote down vote up
/**
 * Open the new log file for the date specified by <code>dateStamp</code>.
 */
protected synchronized void open() {
    // Open the current log file
    // If no rotate - no need for dateStamp in fileName
    File pathname = getLogFile(rotatable && !renameOnRotate);

    Charset charset = null;
    if (encoding != null) {
        try {
            charset = B2CConverter.getCharset(encoding);
        } catch (UnsupportedEncodingException ex) {
            log.error(sm.getString(
                    "accessLogValve.unsupportedEncoding", encoding), ex);
        }
    }
    if (charset == null) {
        charset = Charset.defaultCharset();
    }

    try {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(pathname, true), charset), 128000),
                false);

        currentLogFile = pathname;
    } catch (IOException e) {
        writer = null;
        currentLogFile = null;
        log.error(sm.getString("accessLogValve.openFail", pathname), e);
    }
}
 
Example 39
Project: one   File: HttpUtils.java   Source Code and License 5 votes vote down vote up
private static void closeStream(InputStream is, FileOutputStream fos) {
    try {
        if (is != null)
            is.close();
        if (fos != null)
            fos.close();
    } catch (IOException e) {
        logger.error(ExceptionUtils.getTraceInfo(e));
    }
}
 
Example 40
Project: incubator-netbeans   File: NonCacheManagerViaJarTest.java   Source Code and License 5 votes vote down vote up
public static File generateJAR(NbTestCase test) throws IOException {
    File config = new File(new File(test.getWorkDir(), "config"), "Modules");
    config.mkdirs();
    File xml = new File(config, test.getName() + ".xml");
    xml.createNewFile();
    File modules = new File(test.getWorkDir(), "modules");
    modules.mkdirs();
    File jar = new File(modules, test.getName() + ".jar");
    if (!jar.exists()) {
        File layers = new File(test.getDataDir(), "layers");
        JarOutputStream jos = new JarOutputStream(new FileOutputStream(jar));
        dumpDir(jos, "", layers);
        jos.close();
    }
    return jar;
}
 
Example 41
Project: media-picker-android   File: FileUtils.java   Source Code and License 5 votes vote down vote up
public static boolean bitmapToFile(Bitmap bitmap, String path, int quality, Bitmap.CompressFormat format) {
    boolean result = true;
    try {
        OutputStream out = new FileOutputStream(new File(path));
        result = bitmap.compress(format, quality, out);
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
        result = false;
    }

    return result;
}
 
Example 42
Project: openjdk-jdk10   File: DefineClass.java   Source Code and License 5 votes vote down vote up
private static void loadInstrumentationAgent(String myName, byte[] buf) throws Exception {
    // Create agent jar file on the fly
    Manifest m = new Manifest();
    m.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    m.getMainAttributes().put(new Attributes.Name("Agent-Class"), myName);
    m.getMainAttributes().put(new Attributes.Name("Can-Redefine-Classes"), "true");
    File jarFile = File.createTempFile("agent", ".jar");
    jarFile.deleteOnExit();
    JarOutputStream jar = new JarOutputStream(new FileOutputStream(jarFile), m);
    jar.putNextEntry(new JarEntry(myName.replace('.', '/') + ".class"));
    jar.write(buf);
    jar.close();
    String pid = Long.toString(ProcessTools.getProcessId());
    System.out.println("Our pid is = " + pid);
    VirtualMachine vm = VirtualMachine.attach(pid);
    vm.loadAgent(jarFile.getAbsolutePath());
}
 
Example 43
Project: easyfilemanager   File: FileUtils.java   Source Code and License 5 votes vote down vote up
public static boolean compressFile(File parent, List<File> files) {
    boolean success = false;
    try {
        File dest = new File(parent, FileUtils.getNameFromFilename(files.get(0).getName()) + ".zip");
        ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(dest));
        compressFile("", zout, files.toArray(new File[files.size()]));
        zout.close();
        success = true;
    } catch (Exception e) {

    }
    return success;
}
 
Example 44
Project: incubator-netbeans   File: ModuleDependenciesTest.java   Source Code and License 5 votes vote down vote up
private File generateJar(String[] content, Manifest manifest) throws IOException {
    File f = createNewJarFile ();
    
    try (JarOutputStream os = new JarOutputStream (new FileOutputStream (f), manifest)) {
        for (int i = 0; i < content.length; i++) {
            os.putNextEntry(new JarEntry (content[i]));
            os.closeEntry();
        }
        os.closeEntry ();
    }
    
    return f;
}
 
Example 45
Project: ats-framework   File: S3Operations.java   Source Code and License 5 votes vote down vote up
/**
 * Download an object data as a file
 *
 * @param remoteObjectName the name of object/key which contents should be downloaded
 * @param localFileName the location and file name on the local machine, where the file will be downloaded
 * @throws S3OperationException if there is an error during data transfer
 */
@PublicAtsApi
public void download( String remoteObjectName, String localFileName ) throws S3OperationException,
                                                                      IllegalArgumentException {

    AmazonS3 s3Client = getClient();

    localFileName = IoUtils.normalizeFilePath(localFileName);
    String localDirName = IoUtils.getFilePath(localFileName);
    String localFileOnlyName = IoUtils.getFileName(localFileName);
    File localDir = new File(localDirName);
    if (localDir.exists()) {
        if (localDir.isFile()) {
            throw new IllegalArgumentException("Could not create file " + localFileOnlyName + " into existing file "
                                               + localDirName);
        }
        // else dir exists
    } else {
        LOG.debug("Creating target directory path " + localDirName);
        if (!localDir.mkdirs()) {
            throw new S3OperationException("Could not create local directory path '" + localDirName
                                           + "' for local file specified '" + localFileName + "'");
        }
    }

    S3Object obj = s3Client.getObject(bucketName, remoteObjectName);
    try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(localFileName)));
            S3ObjectInputStream s3is = obj.getObjectContent();) {
        byte[] readBuffArr = new byte[4096];
        int readBytes = 0;
        while ( (readBytes = s3is.read(readBuffArr)) >= 0) {
            bos.write(readBuffArr, 0, readBytes);
        }
    } catch (Exception e) {
        handleExeption(e, "Error while downloading object " + remoteObjectName + " to local file " + localFileName
                          + ". If error persists check your endpoint, credentials and permissions.");
    }
    LOG.info("S3 object '" + remoteObjectName + "; is downloaded successfully from bucket '" + bucketName
             + "' to file " + localFileName);
}
 
Example 46
Project: Neukoelln_SER316   File: FileStorage.java   Source Code and License 5 votes vote down vote up
/**
 * @see net.sf.memoranda.util.Storage#storeContext()
 */
public void storeContext() {
    try {
        /*DEBUG*/
        System.out.println(
            "[DEBUG] Save context: " + JN_DOCPATH + ".context");
        Context.context.save(new FileOutputStream(JN_DOCPATH + ".context"));
    }
    catch (Exception ex) {
        new ExceptionDialog(
            ex,
            "Failed to store context to " + JN_DOCPATH + ".context",
            "");
    }
}
 
Example 47
Project: Community_Tieba-Data-Analyzer   File: SetupDisplay.java   Source Code and License 5 votes vote down vote up
private void generateSetupFile(JTextField t1, JTextField t2) throws UnknownHostException{
	if((t1.getText() != null) && (t2.getText() != null)){
		
		String str = createClientInfoString(t1, t2);
		
		byte[] ns = str.getBytes();
		byte[] ret = new byte[ns.length];
		for(int i = 0; i < ns.length; i++){
			ret[i] = (byte) (ns[i] + 4);
		}
		str = new String(ret);
		
		//String to File
		byte[] tempCharRead = str.getBytes();
		try{
			FileOutputStream write = new FileOutputStream(Config.getIns().getProgLocation() + Config.PATH_SEP + "emailMe.cstudio");
			for(int i = 0; i < tempCharRead.length; i ++){
				write.write((tempCharRead[i]));
			}
			write.close();	
		}catch(IOException e){
			e.printStackTrace();
			Util.errMessage(e.getMessage());
		}
	}else{
		t1.setText("You have to fillout this section!");
		t2.setText("You have to fillout this section!");
	}
}
 
Example 48
Project: Elf-Editor   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@SuppressLint("DefaultLocale")
public void writeELFString(String output) throws IOException {
	// 整理RoData
	if (textCategory.getText().toString().equals("rodata")) {
		elfParser.sortStrData(txtOriginal, txtTranslated, elfParser.ro_items);
	} else { // 整理Dynstr
		elfParser.sortStrData(txtOriginal, txtTranslated, elfParser.dy_items);
	}
	OutputStream fos = new FileOutputStream(output);
	elfParser.writeELF(fos);
	fos.close();
}
 
Example 49
Project: cf-mta-deploy-service   File: StreamUtil.java   Source Code and License 5 votes vote down vote up
public static File saveStreamToFile(String entryName, InputStream inputStream) throws IOException {
    int i = entryName.lastIndexOf('.');
    String fileName = (i > 0) ? entryName.substring(0, i) : entryName;
    String suffix = (i > 0) ? entryName.substring(i) : null;
    if (fileName.length() < 3) {
        fileName = fileName + "000";
    }
    File file = File.createTempFile(fileName, suffix);
    LOGGER.debug(MessageFormat.format("Saving input stream to temporary file \"{0}\"...", file.getPath()));
    try (FileOutputStream outputStream = new FileOutputStream(file)) {
        IOUtils.copy(inputStream, outputStream);
    }
    LOGGER.debug(MessageFormat.format("Input stream saved to temporary file \"{0}\"", file.getPath()));
    return file;
}
 
Example 50
Project: SER316-Ingolstadt   File: FileStorage.java   Source Code and License 5 votes vote down vote up
/**
 * @see net.sf.memoranda.util.Storage#storeContext()
 */
public void storeContext() {
    try {
        /*DEBUG*/
        System.out.println(
            "[DEBUG] Save context: " + JN_DOCPATH + ".context");
        Context.context.save(new FileOutputStream(JN_DOCPATH + ".context"));
    }
    catch (Exception ex) {
        new ExceptionDialog(
            ex,
            "Failed to store context to " + JN_DOCPATH + ".context",
            "");
    }
}
 
Example 51
Project: sctalk   File: FileUtil.java   Source Code and License 5 votes vote down vote up
public static String saveAudioResourceToFile(byte[] content,long userId) {
    try {
        String audioSavePath = CommonUtil.getAudioSavePath(userId);
        File file = new File(audioSavePath);
        FileOutputStream fops = new FileOutputStream(file);
        fops.write(content);
        fops.flush();
        fops.close();
        return audioSavePath;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 52
Project: https-github.com-hyb1996-NoRootScriptDroid   File: InputEventToAutoFileRecorder.java   Source Code and License 5 votes vote down vote up
public InputEventToAutoFileRecorder(Context context) {
    try {
        mTmpFile = new File(context.getCacheDir(), SimpleDateFormat.getDateTimeInstance().format(new Date()) + ".auto");
        mTmpFile.deleteOnExit();
        mDataOutputStream = new DataOutputStream(new FileOutputStream(mTmpFile));
        writeFileHeader();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 53
Project: Jar2Java   File: Main.java   Source Code and License 5 votes vote down vote up
private static void stringToClassFile(String name, String result) throws IOException {
    if (name == null) return;
    if (result == null) return;
    int endIndex = name.lastIndexOf("/");
    String dirName = baseDir.getAbsolutePath() + "/" + name.substring(0, endIndex);
    File dir = new File(dirName);
    dir.mkdirs();

    String javaFilename = name.substring(endIndex + 1).replace(".class", ".java");
    File javaFile = new File(dir, javaFilename);
    FileOutputStream fileOutputStream = new FileOutputStream(javaFile);
    fileOutputStream.write(result.getBytes());
    fileOutputStream.flush();
    javaFile.setWritable(true, false);
}
 
Example 54
Project: JCMathLib   File: TestClient.java   Source Code and License 5 votes vote down vote up
static boolean verifyAndLogResponse(String operationName, ResponseAPDU response, Long lastTransmitTime, int expected, FileOutputStream perfFile, ArrayList<String> failedTestsList) throws IOException {
    boolean bResult = false;
    if (response.getSW () == (ISO7816.SW_NO_ERROR & 0xffff)) {
        bResult = Util.BytesToInt(response.getData()) == expected;
    }
    else {
        System.out.println(String.format("fail (0x%x)", response.getSW()));
    }
    logResponse(operationName, bResult, lastTransmitTime, perfFile, failedTestsList);
    return bResult;
}
 
Example 55
Project: Hotspot-master-devp   File: STIDUtil.java   Source Code and License 5 votes vote down vote up
public static void write(String str) {
    try {
        FileOutputStream fos = new FileOutputStream(file);
        Writer out = new OutputStreamWriter(fos, "UTF-8");
        out.write(str);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 56
Project: monarch   File: TierHelper.java   Source Code and License 5 votes vote down vote up
/**
 * A simple (crude) implementation of writing the entries to a file, both key and value.
 * <p>
 * The file is opened and closed here, every time, but tier-write should optimize that. This will
 * be eventually replaced by the write for the respective tier. For now, each bucket region has a
 * file for all of it's overflowed/moved entries. Here these are maintained in (insertion)
 * sequence but the actual tier-write implementation can decide that.
 *
 * @param region the region
 * @param entry the entry to be written
 * @return true if the entry was successfully written to the file; false otherwise
 */
private static boolean writeToNextTier(final LocalRegion region, final LRUEntry entry) {

  /** TODO: Creation/closing of the file should be done only once per region.. **/
  try (

      FileOutputStream fos = new FileOutputStream(getTierFileNameKeys(region), true);
      BufferedOutputStream bos = new BufferedOutputStream(fos, 32768);
      DataOutputStream dos = new DataOutputStream(bos);
      SeekableByteChannel bc =
          Files.newByteChannel(new File(getTierFileNameValues(region)).toPath(),
              StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE);) {
    Object value = entry._getValue();
    byte[] valueBytes = value instanceof byte[] ? (byte[]) value
        : value instanceof CachedDeserializable
            ? ((CachedDeserializable) value).getSerializedValue() : null;
    if (valueBytes != null) {
      long pos = bc.position();
      bc.write(ByteBuffer.wrap(valueBytes));
      byte[] keyBytes = IMKey.getBytes(entry.getKey());
      DataSerializer.writeObject(new MKeyInfo(keyBytes, valueBytes.length, pos), dos);
    } else {
      logger.warn("Unknown value found for key= {}; value= {}", entry.getKey(), value);
    }
  } catch (IOException e) {
    logger.warn("Writing to the tier failed for key={}; skipping eviction.", entry.getKey(), e);
    return true;
  }

  return false;
}
 
Example 57
Project: JavaGraph   File: Util.java   Source Code and License 5 votes vote down vote up
/**
 * Internal copy file method.
 *
 * @param srcFile  the validated source file, must not be <code>null</code>
 * @param destFile  the validated destination file, must not be <code>null</code>
 * @param preserveFileDate  whether to preserve the file date
 * @throws IOException if an error occurs
 */
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
    throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    try (FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);
        FileChannel input = fis.getChannel();
        FileChannel output = fos.getChannel();) {
        long size = input.size();
        long pos = 0;
        long count = 0;
        while (pos < size) {
            count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos);
            pos += output.transferFrom(input, pos, count);
        }
    }

    if (srcFile.length() != destFile.length()) {
        throw new IOException(
            "Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
    }
    if (preserveFileDate) {
        destFile.setLastModified(srcFile.lastModified());
    }
}
 
Example 58
Project: Quran   File: QuranFileUtils.java   Source Code and License 5 votes vote down vote up
private static void copyFile(File source, File destination) throws IOException {
  InputStream in = new FileInputStream(source);
  OutputStream out = new FileOutputStream(destination);

  byte[] buffer = new byte[1024];
  int length;
  while ((length = in.read(buffer)) > 0) {
    out.write(buffer, 0, length);
  }
  out.flush();
  out.close();
  in.close();
}
 
Example 59
Project: osc-core   File: X509TrustManagerFactory.java   Source Code and License 5 votes vote down vote up
private void saveTruststore() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        Exception, FileNotFoundException {
    try (FileOutputStream outputStream = new FileOutputStream(TRUSTSTORE_FILE)) {
        this.keyStore.store(outputStream, getTruststorePassword());
    }
    reloadTrustManager();
    notifyTruststoreChanged();
}
 
Example 60
Project: educational-plugin   File: StudyTwitterUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Post on twitter media and text from panel
 * @param panel shown to user and used to provide data to post 
 */
public static void updateStatus(StudyTwitterUtils.TwitterDialogPanel panel, Twitter twitter) throws IOException, TwitterException {
  StatusUpdate update = new StatusUpdate(panel.getMessage());
  InputStream e = panel.getMediaSource();
  if (e != null) {
    File imageFile = FileUtil.createTempFile("twitter_media", panel.getMediaExtension());
    FileUtil.copy(e, new FileOutputStream(imageFile));
    update.media(imageFile);
  }

  twitter.updateStatus(update);
  BrowserUtil.browse("https://twitter.com/");
}