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: fingerblox   File: Utils.java   View source code 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 2
Project: jdk8u-jdk   File: GetRoot.java   View source code 7 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 3
Project: APITools   File: PubUtils.java   View source code 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 4
Project: BibliotecaPS   File: BlobTest.java   View source code 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 5
Project: ImageLoaderSupportGif   File: HomeActivity.java   View source code 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 6
Project: SER316-Ingolstadt   File: FileStorage.java   View source code 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 7
Project: boohee_v5.6   File: DiskBasedCache.java   View source code 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 8
Project: openjdk-jdk10   File: B7050028.java   View source code 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 9
Project: EnchantedFortress   File: HighScores.java   View source code 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 10
Project: chromium-net-for-android   File: UploadDataProvidersTest.java   View source code 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 11
Project: creacoinj   File: BuildCheckpoints.java   View source code 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 12
Project: Allshare   File: MainActivity.java   View source code 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 13
Project: android-project-gallery   File: RangeFileAsyncHttpResponseHandler.java   View source code 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 14
Project: Selector   File: ImageCacheUtils.java   View source code 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 15
Project: Tarski   File: MiniSatExternal.java   View source code 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 16
Project: hadoop   File: TestSharedFileDescriptorFactory.java   View source code 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 17
Project: JavaGraph   File: SaveAction.java   View source code 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 18
Project: GravityBox   File: KeyguardImageService.java   View source code 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 19
Project: JInsight   File: RuleScriptGenerator.java   View source code 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 20
Project: calcite-avatica   File: SslDriverTest.java   View source code 6 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 21
Project: boqa   File: WordNetParserTest.java   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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;
}