Java 类java.io.FileOutputStream 实例源码

项目:fingerblox    文件:Utils.java   
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);
    }
}
项目:BibliotecaPS    文件:BlobTest.java   
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();
}
项目:jdk8u-jdk    文件:GetRoot.java   
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);
}
项目:APITools    文件:PubUtils.java   
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);
    }
}
项目:ImageLoaderSupportGif    文件:HomeActivity.java   
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();
}
项目:incubator-netbeans    文件:NonCacheManagerViaJarTest.java   
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;
}
项目:openjdk-jdk10    文件:DefineClass.java   
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());
}
项目:SER316-Ingolstadt    文件:FileStorage.java   
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,
            "");
    }
}
项目:boohee_v5.6    文件:DiskBasedCache.java   
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());
        }
    }
}
项目:openjdk-jdk10    文件:B7050028.java   
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()));
}
项目:EnchantedFortress    文件:HighScores.java   
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);
    }
}
项目:chromium-net-for-android    文件:UploadDataProvidersTest.java   
@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();
    }
}
项目:creacoinj    文件:BuildCheckpoints.java   
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() + "'.");
}
项目:Allshare    文件:MainActivity.java   
@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();
        }
    }
}
项目:android-project-gallery    文件:RangeFileAsyncHttpResponseHandler.java   
@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;
}
项目:Selector    文件:ImageCacheUtils.java   
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();
    }
项目:Tarski    文件:MiniSatExternal.java   
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);
    }
}
项目:hadoop    文件:TestSharedFileDescriptorFactory.java   
@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);
}
项目:JavaGraph    文件:SaveAction.java   
/**
 * 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;
}
项目:GravityBox    文件:KeyguardImageService.java   
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;
    }
}
项目:JInsight    文件:RuleScriptGenerator.java   
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();
}
项目:calcite-avatica    文件:SslDriverTest.java   
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);
  }
}
项目:boqa    文件:WordNetParserTest.java   
@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() + "\"";
            }
        });
}
项目:AndroidDBForData    文件:IOHelper.java   
/**
 * 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();
}
项目:MetadataEditor    文件:FlacInfoReader.java   
/**
 * 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;
}
项目:CoolClock    文件:FileUtils.java   
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();
    }
}
项目:CDN-FX-2.2    文件:XMLUpdater.java   
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;
    }
}
项目:Reer    文件:LocalDirectoryBuildCache.java   
@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);
            }
        }
    });
}
项目:Nird2    文件:FilePlugin.java   
@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;
    }
}
项目:sAINT    文件:sAINT.java   
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();
    }
}
项目:Cubeland    文件:SavingSystem.java   
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!");
    }
}
项目:SparkSeq    文件:AdaptiveHuffmanCompress.java   
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();
    }
}
项目:Hotspot-master-devp    文件:BitmapCommonUtils.java   
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();
            }
        }
    }
项目:mir2.core    文件:WIL.java   
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();
}
项目:Ec2m    文件:CamaraActivity.java   
@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;
            }
        }
项目:CorePatch    文件:GdiffTest.java   
/**
 * 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);
}
项目:MobiRNN-EMDL17    文件:Util.java   
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;
}
项目:Dahlem_SER316    文件:Configuration.java   
public static void saveConfig() {
  try {
  config.save(new FileOutputStream(configPath));
  }
  catch (Exception e) {
   new ExceptionDialog(e, "Failed to save a configuration file:<br>"+configPath, "");
  }
}
项目:Moenagade    文件:DeferredFileOutputStream.java   
/**
 * 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;
}
项目:apache-tomcat-7.0.73-with-comment    文件:AccessLogValve.java   
/**
 * 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);
    }
}