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

The following examples show how to use java.io.FileOutputStream#flush() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private void writeToDisk(HttpEntity entity, String file) throws IllegalStateException, IOException
/**
 * writes a HTTP entity to the specified filename and location on disk
 */
{
    //int i = 0;
    String FilePath = "/sdcard/" + file;
    InputStream in = entity.getContent();
    byte buff[] = new byte[1024];
    FileOutputStream out =
            new FileOutputStream(FilePath);
   do {
        int numread = in.read(buff);
        if (numread <= 0)
            break;
        out.write(buff, 0, numread);
        //i++;
    } while (true);
    out.flush();
    out.close();
}
 
Example 2
Source Project: android-storage   File: Storage.java    License: Apache License 2.0 6 votes vote down vote up
public void appendFile(String path, byte[] bytes) {
    if (!isFileExist(path)) {
        Log.w(TAG, "Impossible to append content, because such file doesn't exist");
        return;
    }

    try {
        FileOutputStream stream = new FileOutputStream(new File(path), true);
        stream.write(bytes);
        stream.write(System.getProperty("line.separator").getBytes());
        stream.flush();
        stream.close();
    } catch (IOException e) {
        Log.e(TAG, "Failed to append content to file", e);
    }
}
 
Example 3
Source Project: AndroidMathKeyboard   File: TeXFormula.java    License: Apache License 2.0 6 votes vote down vote up
public void createImage(Bitmap.CompressFormat format, int style,
		float size, String out, Integer bg, Integer fg, boolean transparency)
		throws IOException {
	TeXIcon icon = createTeXIcon(style, size);
	icon.setInsets(new Insets(1, 1, 1, 1));
	int w = icon.getIconWidth(), h = icon.getIconHeight();

	Bitmap image = Bitmap.createBitmap(w, h, Config.ARGB_8888);
	Canvas g2 = new Canvas(image);
	if (bg != null) {
		Paint st = new Paint();
		st.setStyle(Style.FILL_AND_STROKE);
		st.setColor(bg);
		g2.drawRect(0, 0, w, h, st);
	}

	icon.setForeground(fg == null ? Color.BLACK : fg);
	icon.paintIcon(g2, 0, 0);
	File file = new File(out);
	FileOutputStream imout = new FileOutputStream(file);
	image.compress(format, 90, imout);
	imout.flush();
	imout.close();
}
 
Example 4
Source Project: xposed-aweme   File: DialogUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean saveImage2SDCard(String qrSavePath, Bitmap qrBitmap) {

        try {
            File qrFile = new File(qrSavePath);

            File parentFile = qrFile.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }

            FileOutputStream fos = new FileOutputStream(qrFile);
            qrBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
            return true;
        } catch (IOException e) {
            Alog.e("保存失败", e);
        }
        return false;
    }
 
Example 5
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        long contentLength = entity.getContentLength();
        FileOutputStream buffer = new FileOutputStream(getTargetFile());
        if (instream != null) {
            try {
                byte[] tmp = new byte[BUFFER_SIZE];
                int l, count = 0;
                // do not send messages if request has been cancelled
                while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                    count += l;
                    buffer.write(tmp, 0, l);
                    sendProgressMessage(count, (int) contentLength);
                }
            } finally {
                instream.close();
                buffer.flush();
                buffer.close();
            }
        }
    }
    return null;
}
 
Example 6
/**
 * Save binary data on local file system.
 *
 * @param fileName filename
 * @param data     binary data
 * @return stored file
 * @throws IOException if the specified binary data could not be stored.
 */
private File saveFile(final String fileName, final byte[] data) throws IOException {
    File dir = getContext().getFilesDir();
    File file = new File(dir, generateFileName());
    if (!file.exists()) {
        if (!file.createNewFile()) {
            throw new IOException("File is not be stored: " + fileName);
        }
    }
    FileOutputStream fos = new FileOutputStream(file);
    try {
        fos.write(data);
        fos.flush();
    } finally {
        fos.close();
    }
    return file;
}
 
Example 7
Source Project: BotLibre   File: LoginBean.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public String getAvatarImage(AvatarImage avatar) {
	if (avatar != null) {
		String fileName = "avatars/" + "a" + avatar.getId() + ".jpg";
		String path = LoginBean.outputFilePath + "/" + fileName;
		byte[] image = avatar.getImage();
		if (image != null) {
			File file = new File(path);
			if (!file.exists()) {
				try {
					FileOutputStream stream = new FileOutputStream(file);
					stream.write(image);
					stream.flush();
					stream.close();
				} catch (IOException exception) {
					error(exception);
					return "images/bot.png";
				}
			}
			return fileName;
		}
	}
	return "images/bot.png";
}
 
Example 8
Source Project: scanvine-android   File: SVDownloadManager.java    License: MIT License 6 votes vote down vote up
private boolean fetchFile(Context context, String urlString, File localFile) {
    try {
        InputStream is = getStreamFor(urlString);
        FileOutputStream out = new FileOutputStream(localFile); 
        byte[] buffer = new byte[4096];
        int len = 0;
        while ((len = is.read(buffer)) >=0) {
            out.write(buffer, 0, len);
        }
        out.flush();    
        out.close();
        return true;
    } catch (Exception ex) {
        Log.e(""+this, "fetchFile failed", ex);
        return false;
    }
}
 
Example 9
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        long contentLength = entity.getContentLength();
        FileOutputStream buffer = new FileOutputStream(getTargetFile(), this.append);
        if (instream != null) {
            try {
                byte[] tmp = new byte[BUFFER_SIZE];
                int l, count = 0;
                // do not send messages if request has been cancelled
                while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                    count += l;
                    buffer.write(tmp, 0, l);
                    sendProgressMessage(count, (int) contentLength);
                }
            } finally {
                AsyncHttpClient.silentCloseInputStream(instream);
                buffer.flush();
                AsyncHttpClient.silentCloseOutputStream(buffer);
            }
        }
    }
    return null;
}
 
Example 10
Source Project: gemfirexd-oss   File: DatabaseClasses.java    License: Apache License 2.0 5 votes vote down vote up
private static void WriteClassFile(String fullyQualifiedName, ByteArray bytecode, Throwable t) {

		// get the un-qualified name and add the extension
        int lastDot = fullyQualifiedName.lastIndexOf((int)'.');
        String filename = fullyQualifiedName.substring(lastDot+1,fullyQualifiedName.length()).concat(".class");

		Object env = Monitor.getMonitor().getEnvironment();
		File dir = env instanceof File ? (File) env : null;

		File classFile = FileUtil.newFile(dir,filename);

		// find the error stream
		HeaderPrintWriter errorStream = Monitor.getStream();

		try {
			FileOutputStream fis = new FileOutputStream(classFile);
			fis.write(bytecode.getArray(),
				bytecode.getOffset(), bytecode.getLength());
			fis.flush();
			if (t!=null) {				
				errorStream.printlnWithHeader(MessageService.getTextMessage(MessageId.CM_WROTE_CLASS_FILE, fullyQualifiedName, classFile, t));
			}
			fis.close();
		} catch (IOException e) {
			if (SanityManager.DEBUG)
				SanityManager.THROWASSERT("Unable to write .class file");
		}
	}
 
Example 11
public void saveImage(Product product) {
    ActivityCompat.requestPermissions((ProductActivity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 666);
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/pos-barcodes");
    myDir.mkdirs();
    String text = "noName";
    if (!product.getProductName().isEmpty())
        text = product.getProductName();
    String fname = "Image-" + text + ".jpg";
    File file = new File(myDir, fname);
    if (file.exists()) file.delete();
    try {
        Bitmap finalBitmap = getBarCodeBitmap(product.getBarCode());
        if (finalBitmap != null) {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            SweetAlertBox.getInstance().showSuccessPopUp(context, context.getString(R.string.barcode_saved), context.getString(R.string.image_saved_to) + file.getPath());
            ToastHelper.showToast(context, "Barcode Saved!", Toast.LENGTH_SHORT);
        } else {
            ToastHelper.showToast(context, "Barcode is empty, generate first to save!", Toast.LENGTH_LONG);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 12
Source Project: ofx4j   File: ReassignLocalIds.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  LocalResourceFIDataStore store = new LocalResourceFIDataStore();
  for (FinancialInstitutionData data : store.getInstitutionDataList()) {
    BaseFinancialInstitutionData dataImpl = (BaseFinancialInstitutionData) data;
    dataImpl.setId(String.valueOf(dataImpl.hashCode()));
  }

  FileOutputStream out = new FileOutputStream("/tmp/institutions.xml");
  store.storeData(out);
  out.flush();
  out.close();
}
 
Example 13
Source Project: letv   File: rcrccr.java    License: Apache License 2.0 5 votes vote down vote up
public boolean bщщ0449щ0449щ() {
    Log.d(b042D042DЭ042D042D042D, "Policy File Length: " + this.mConnection.getContentLength());
    try {
        InputStream inputStream = this.mConnection.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(this.mTargetLocation);
        if (((b044A044A044Aъъ044A + bъъъ044Aъ044A) * b044A044A044Aъъ044A) % b044Aъъ044Aъ044A != b044A044Aъ044Aъ044A) {
            b044A044A044Aъъ044A = 35;
            b044A044Aъ044Aъ044A = bъ044Aъ044Aъ044A();
        }
        byte[] bArr = new byte[1024];
        while (true) {
            try {
                int read = inputStream.read(bArr);
                if (read != -1) {
                    fileOutputStream.write(bArr, 0, read);
                }
            } catch (IOException e) {
                Log.e(b042D042DЭ042D042D042D, "Error downloading pm file");
            }
            try {
                break;
            } catch (IOException e2) {
                Log.e(b042D042DЭ042D042D042D, "Fail to close input/output stream");
            }
        }
        fileOutputStream.flush();
        fileOutputStream.close();
        inputStream.close();
        return true;
    } catch (FileNotFoundException e3) {
        Log.e(b042D042DЭ042D042D042D, "Target policy file is not found.");
        return false;
    } catch (IOException e4) {
        e4.printStackTrace();
        return false;
    }
}
 
Example 14
Source Project: Ngram-Graphs   File: AutoSummENGGui.java    License: Apache License 2.0 5 votes vote down vote up
/** Save GUI settings in file. */
private void saveSettings() {
    Properties pOut = new Properties();
    // Dirs
    pOut.setProperty("ModelDir", ModelsRootDirEdt.getText());
    pOut.setProperty("SummaryDir", SummariesRootDirEdt.getText());
    pOut.setProperty("OutputFile", OutputFileEdt.getText());
    
    // Global settings
    pOut.setProperty("Threads", ThreadCntEdt.getValue().toString());
    pOut.setProperty("Silent", String.valueOf(SilentChk.isSelected()));
    pOut.setProperty("ShowProgress", String.valueOf(ProgressChk.isSelected()));
    pOut.setProperty("DoWord", String.valueOf(DoWordChk.isSelected()));
    pOut.setProperty("DoChar", String.valueOf(DoCharChk.isSelected()));
    pOut.setProperty("Use", OccurencesChk.isSelected() ? "Occurences" : "Distros");
    // Char settings
    pOut.setProperty("CharMin", String.valueOf(CharMinEdt.getValue()));
    pOut.setProperty("CharMax", String.valueOf(CharMaxEdt.getValue()));
    pOut.setProperty("CharDist", String.valueOf(CharDistEdt.getValue()));
    // Word settings
    pOut.setProperty("WordMin", String.valueOf(WordMinEdt.getValue()));
    pOut.setProperty("WordMax", String.valueOf(WordMaxEdt.getValue()));
    pOut.setProperty("WordDist", String.valueOf(WordDistEdt.getValue()));
    
    // Save
    try {
        FileOutputStream fsOut = new FileOutputStream("AutoSummENGGUI.properties");
        pOut.storeToXML(fsOut, "");
        fsOut.flush();
        fsOut.close();
    }
    catch (IOException ioe) {
        ioe.printStackTrace(System.err);
    }

}
 
Example 15
Source Project: unitime   File: DataImportAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void executeDataExchange() throws Exception {
      	ExportType type = iForm.getExportType();
      	if (type == ExportType.SESSION) {
  			FileOutputStream out = new FileOutputStream(createOutput("session", "dat"));
  			try {
  				SessionBackupInterface backup = (SessionBackupInterface)Class.forName(ApplicationProperty.SessionBackupInterface.value()).getConstructor().newInstance();
  				backup.backup(out, this, getSessionId());
  			} finally {
  				out.close();
  			}
      	} else {
              Properties params = new Properties();
              type.setOptions(params);
              Document document = DataExchangeHelper.exportDocument(type.getType(), getSession(), params, this);
              if (document==null) {
                  error("XML document not created: unknown reason.");
              } else {
                  FileOutputStream fos = new FileOutputStream(createOutput(type.getType(), "xml"));
                  try {
                      (new XMLWriter(fos,OutputFormat.createPrettyPrint())).write(document);
                      fos.flush();
                  } finally {
                  	fos.close();
                  }
              }
      	}
}
 
Example 16
@Before
public void setUp() throws IOException {
  // Creates the following resources:
  // 1. The old file, on disk (and in-memory, for convenience).
  // 2. The new file, in memory only (for comparing results at the end).
  // 3. The patch, in memory.

  File tempFile = File.createTempFile("foo", "bar");
  tempDir = tempFile.getParentFile();
  tempFile.delete();
  oldFile = File.createTempFile("fbfv1dat", "old");
  oldFile.deleteOnExit();

  // Write the old file to disk:
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  buffer.write(UNCOMPRESSED_HEADER);
  buffer.write(COMPRESSED_OLD_CONTENT);
  buffer.write(UNCOMPRESSED_TRAILER);
  oldFileBytes = buffer.toByteArray();
  FileOutputStream out = new FileOutputStream(oldFile);
  out.write(oldFileBytes);
  out.flush();
  out.close();

  // Write the delta-friendly old file to a byte array
  buffer = new ByteArrayOutputStream();
  buffer.write(UNCOMPRESSED_HEADER);
  buffer.write(UNCOMPRESSED_OLD_CONTENT);
  buffer.write(UNCOMPRESSED_TRAILER);
  expectedDeltaFriendlyOldFileBytes = buffer.toByteArray();

  // Write the new file to a byte array
  buffer = new ByteArrayOutputStream();
  buffer.write(UNCOMPRESSED_HEADER);
  buffer.write(COMPRESSED_NEW_CONTENT);
  buffer.write(UNCOMPRESSED_TRAILER);
  expectedNewBytes = buffer.toByteArray();

  // Finally, write the patch that should transform old to new
  patchBytes = writePatch();

  // Initialize fake delta applier to mock out dependency on bsdiff
  fakeApplier = new FileByFileV1DeltaApplier(tempDir) {
        @Override
        protected DeltaApplier getDeltaApplier() {
          return new FakeDeltaApplier();
        }
      };
}
 
Example 17
/**
 * 释放被加壳的apk文件,so文件
 *
 * @param data
 * @throws IOException
 */
private void splitPayLoadFromDex(byte[] data) throws IOException {
    byte[] apkdata = decrypt(data);  //解壳程序的dex并没有加密,所以也不需要解密
    int ablen = apkdata.length;
    //取被加壳apk的长度   这里的长度取值,对应加壳时长度的赋值都可以做些简化
    byte[] dexlen = new byte[4];
    System.arraycopy(apkdata, ablen - 4, dexlen, 0, 4);
    ByteArrayInputStream bais = new ByteArrayInputStream(dexlen);
    DataInputStream in = new DataInputStream(bais);
    int readInt = in.readInt();
    System.out.println(Integer.toHexString(readInt));
    byte[] newdex = new byte[readInt];
    //把被加壳apk内容拷贝到newdex中
    System.arraycopy(apkdata, ablen - 4 - readInt, newdex, 0, readInt);
    //这里应该加上对于apk的解密操作,若加壳是加密处理的话
    //?
    //写入apk文件
    File file = new File(apkFileName);
    try {
        FileOutputStream localFileOutputStream = new FileOutputStream(file);
        localFileOutputStream.write(newdex);
        localFileOutputStream.close();


    } catch (IOException localIOException) {
        throw new RuntimeException(localIOException);
    }

    //分析被加壳的apk文件
    ZipInputStream localZipInputStream = new ZipInputStream(
            new BufferedInputStream(new FileInputStream(file)));
    while (true) {
        ZipEntry localZipEntry = localZipInputStream.getNextEntry();//不了解这个是否也遍历子目录,看样子应该是遍历的
        if (localZipEntry == null) {
            localZipInputStream.close();
            break;
        }
        //取出被加壳apk用到的so文件,放到 libPath中(data/data/包名/payload_lib)
        String name = localZipEntry.getName();
        if (name.startsWith("lib/") && name.endsWith(".so")) {
            File storeFile = new File(libPath + "/"
                    + name.substring(name.lastIndexOf('/')));
            storeFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(storeFile);
            byte[] arrayOfByte = new byte[1024];
            while (true) {
                int i = localZipInputStream.read(arrayOfByte);
                if (i == -1)
                    break;
                fos.write(arrayOfByte, 0, i);
            }
            fos.flush();
            fos.close();
        }
        localZipInputStream.closeEntry();
    }
    localZipInputStream.close();
}
 
Example 18
Source Project: Android-Commons   File: ViewScreenshot.java    License: Apache License 2.0 4 votes vote down vote up
private static File saveBitmapToPublicStorage(final Context context, final String filenameWithoutExtension, final Bitmap bitmap, final int format) throws Exception {
	// get the output directory
	final File applicationDir = context.getExternalFilesDir(null);
	final File libraryDir = new File(applicationDir, "im.delight.android.commons");
	final File outputDir = new File(libraryDir, "screenshots");

	// create the output directory if it doesn't exist
	outputDir.mkdirs();

	// create the .nomedia file which prevents images from showing up in gallery
	try {
		final File noMedia = new File(outputDir, NO_MEDIA_FILENAME);
		noMedia.createNewFile();
	}
	// ignore if the file does already exist or cannot be created
	catch (Exception e) { }

	// set up variables for file format
	final Bitmap.CompressFormat bitmapFormat;
	final String fileExtension;
	if (format == FORMAT_JPEG) {
		bitmapFormat = Bitmap.CompressFormat.JPEG;
		fileExtension = ".jpg";
	}
	else if (format == FORMAT_PNG) {
		bitmapFormat = Bitmap.CompressFormat.PNG;
		fileExtension = ".png";
	}
	else {
		throw new Exception("Unknown format: "+format);
	}

	// get a reference to the new file
	final File outputFile = new File(outputDir, filenameWithoutExtension + fileExtension);
	// if the output file already exists
	if (outputFile.exists()) {
		// delete it first
		outputFile.delete();
	}
	// create an output stream for the new file
	final FileOutputStream outputStream = new FileOutputStream(outputFile);
	// write the data to the new file
	bitmap.compress(bitmapFormat, 90, outputStream);
	// flush the output stream
	outputStream.flush();
	// close the output stream
	outputStream.close();

	// return the file reference
	return outputFile;
}
 
Example 19
/**
 * Teste de coassinatura desanexada com envio do conteúdo
 */
//@Test
public void testSignCoDetached() {
	try {

		System.out.println("******** TESTANDO COM CONTEÚDO *****************");

		// INFORMAR o arquivo
		String fileDirName = "caminha do arquivo do conteudo";
		String fileSignatureDirName = "caminho do arquivo com a(s) assinatura(s) .p7s";
				
		byte[] fileToSign = readContent(fileDirName);
		byte[] signatureFile = readContent(fileSignatureDirName);

		// quando certificado em arquivo, precisa informar a senha
		char[] senha = "senha".toCharArray();

		// Para certificado em Neo Id e windows
		 KeyStore ks = getKeyStoreTokenBySigner();

		// Para certificado em Token
		// KeyStore ks = getKeyStoreToken();

		

		// Para certificado em arquivo A1
		// KeyStore ks = getKeyStoreFile();
		
		
		// Para certificados no so windows (mascapi)
		// KeyStore ks = getKeyStoreOnWindows();

		String alias = getAlias(ks);
		
		/* Parametrizando o objeto doSign */
		PKCS7Signer signer = PKCS7Factory.getInstance().factoryDefault();
		signer.setCertificates(ks.getCertificateChain(alias));

		// para token
		signer.setPrivateKey((PrivateKey) ks.getKey(alias, null));

		// para arquivo
		// signer.setPrivateKey((PrivateKey) ks.getKey(alias, senha));
		// politica sem carimbo de tempo
		signer.setSignaturePolicy(PolicyFactory.Policies.AD_RB_CADES_2_3);
		// com carimbo de tempo
		//signer.setSignaturePolicy(PolicyFactory.Policies.AD_RT_CADES_2_3);

		// para mudar o algoritimo
		signer.setAlgorithm(SignerAlgorithmEnum.SHA512withRSA);
		if (org.demoiselle.signer.core.keystore.loader.configuration.Configuration.getInstance().getSO().toLowerCase().indexOf("indows") > 0) {
			signer.setAlgorithm(SignerAlgorithmEnum.SHA256withRSA);
		}

		/* Realiza a assinatura do conteudo */
		System.out.println("Efetuando a  assinatura do conteudo");
		// Assinatura desatachada
		byte[] signature = signer.doDetachedSign(fileToSign, signatureFile);
		File file = new File(fileDirName + "-co_detached.p7s");
		FileOutputStream os = new FileOutputStream(file);
		os.write(signature);
		os.flush();
		os.close();
		System.out.println("------------------ ok --------------------------");
		assertTrue(true);
	} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | IOException ex) {
		ex.printStackTrace();
		assertTrue(false);
	}
}
 
Example 20
Source Project: LockDemo   File: OcrUtils.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 将bitmap位图保存到path路径下,图片格式为Bitmap.CompressFormat.JPEG,质量为100
 *
 * @param bitmap
 * @param path
 * @param quality 压缩的比率(1-100)
 */

@SuppressWarnings("ResultOfMethodCallIgnored")
public static boolean saveBitmap(Bitmap bitmap,
                                 String path,
                                 int quality) {

    try {

        File file = new File(path);

        File parent = file.getParentFile();

        if (!parent.exists()) {

            parent.mkdirs();

        }

        // if(file.exists()){
        // FileUtil.deleteFile(file);
        // }

        FileOutputStream fos = new FileOutputStream(file);

        boolean b = bitmap.compress(Bitmap.CompressFormat.JPEG,
                quality,
                fos);
        fos.flush();

        fos.close();

        return b;

    } catch (IOException e) {

        e.printStackTrace();

    } finally {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.isRecycled();
        }
    }

    return false;

}