/** * read from input stream,write into output stream * * @param fileInStream InputStream * @param fileOutStream SvnFileOutputStream */ public static void streamCopy(InputStream fileInStream, FileOutputStream fileOutStream) throws Exception { if (null != fileInStream && null != fileOutStream) { try { byte[] tmpBuf = new byte[BUFFER_SIZE]; int tmpLen = 0; while ((tmpLen = fileInStream.read(tmpBuf)) > 0) { fileOutStream.write(tmpBuf, 0, tmpLen); } fileOutStream.flush(); fileOutStream.close(); fileOutStream = null; fileInStream.close(); fileInStream = null; } catch (Exception e) { if (null != fileInStream) { fileInStream.close(); fileInStream = null; } if (null != fileOutStream) { fileOutStream.flush(); fileOutStream.close(); fileOutStream = null; } throw new Exception("error in write into output stream."); } } }
public void getDrugs(String writepath) throws IOException { FileOutputStream outputStream = new FileOutputStream(new File(writepath)); // int id = 1, max = 10601; int id = 1, max = 10808; // 表头 outputStream.write(("ID\tName\tFormula\tExact mass\tMol weight\tOther DBs\n").getBytes()); // 注意flush outputStream.flush(); DecimalFormat df = new DecimalFormat("00000"); String url = ""; while (id <= max) { url = "http://www.kegg.jp/dbget-bin/www_bget?dr:D" + df.format(id); System.out.println(url); String result = getContentPr(url); if (result != null && result != "") { outputStream.write(("D" + df.format(id) + "\t" + result + "\n").getBytes()); // 注意flush outputStream.flush(); } id++; } outputStream.flush(); outputStream.close(); }
/** * read from input stream,write into output stream * * @param fileInStream * @param fileOutStream */ public static void write(SvnFileInputStream fileInStream, FileOutputStream fileOutStream) throws Exception { if (null != fileInStream && null != fileOutStream) { try { byte[] tmp = new byte[BUFFER_SIZE]; int k = 0; while ((k = fileInStream.read(tmp)) > -1) { fileOutStream.write(tmp, 0, k); } fileOutStream.flush(); fileOutStream.close(); fileOutStream = null; fileInStream.close(); fileInStream = null; } catch (Exception e) { if (null != fileInStream) { fileInStream.close(); fileInStream = null; } if (null != fileOutStream) { fileOutStream.flush(); fileOutStream.close(); fileOutStream = null; } throw new Exception("error in write into output stream."); } } }
private void download(final String url, File file) throws IOException { URL u = new URL(url); HttpURLConnection huc = (HttpURLConnection) u.openConnection(); huc.setRequestMethod("GET"); huc.setReadTimeout(0); final long start = System.currentTimeMillis(); long end; InputStream is = huc.getInputStream(); int c; byte[] ba = new byte[LINE.length() + 6]; FileOutputStream fos = new FileOutputStream(file); try { while ((c = is.read(ba)) != -1) { fos.write(ba, 0, c); fos.flush(); Thread.sleep(100); } is.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } finally { end = System.currentTimeMillis(); fos.flush(); fos.close(); } Assert.assertTrue("Should take more than 30 seconds", end - start >= 30000); }
/** * Web表单文件上传 单个/批量同理 * * @param * @return */ public ActionForward doUpload( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { BaseActionForm cForm = (BaseActionForm) form; // 单个文件,如果是多个就cForm.getFile2()....支持最多5个文件 FormFile myFile = cForm.getFile1(); // 获取web应用根路径,也可以直接指定服务器任意盘符路径 String savePath = getServlet().getServletContext().getRealPath("/") + "/upload/"; // String savePath = "d:/upload/"; // 检查路径是否存在,如果不存在则创建之 File file = new File(savePath); if (!file.exists()) { file.mkdir(); } // 文件按天归档 savePath = savePath + G4Utils.getCurDate() + "/"; File file1 = new File(savePath); if (!file1.exists()) { file1.mkdir(); } // 文件真实文件名 String fileName = myFile.getFileName(); // 我们一般会根据某种命名规则对其进行重命名 // String fileName = ; File fileToCreate = new File(savePath, fileName); // 检查同名文件是否存在,不存在则将文件流写入文件磁盘系统 if (!fileToCreate.exists()) { FileOutputStream os = new FileOutputStream(fileToCreate); os.write(myFile.getFileData()); os.flush(); os.close(); } else { // 此路径下已存在同名文件,是否要覆盖或给客户端提示信息由你自己决定 FileOutputStream os = new FileOutputStream(fileToCreate); os.write(myFile.getFileData()); os.flush(); os.close(); } // 我们通常还会把这个文件的相关信息持久化到数据库 Dto inDto = cForm.getParamAsDto(request); inDto.put( "title", G4Utils.isEmpty(inDto.getAsString("title")) ? fileName : inDto.getAsString("title")); inDto.put("filesize", myFile.getFileSize()); inDto.put("path", savePath + fileName); demoService.doUpload(inDto); setOkTipMsg("文件上传成功", response); return mapping.findForward(null); }
private void testKieModuleMetaDataInMemoryUsingPOM(boolean useTypeDeclaration) throws Exception { // Build a KieModule jar, deploy it into local Maven repository KieServices ks = KieServices.Factory.get(); ReleaseId dependency = ks.newReleaseId("org.drools", "drools-core", "5.5.0.Final"); ReleaseId releaseId = ks.newReleaseId("org.kie", "metadata-test", "1.0-SNAPSHOT"); InternalKieModule kieModule = createKieJarWithClass(ks, releaseId, useTypeDeclaration, 2, 7, dependency); String pomText = getPom(dependency); File pomFile = new File( System.getProperty("java.io.tmpdir"), MavenRepository.toFileName(releaseId, null) + ".pom"); try { FileOutputStream fos = new FileOutputStream(pomFile); fos.write(pomText.getBytes()); fos.flush(); fos.close(); } catch (IOException e) { throw new RuntimeException(e); } MavenRepository.getMavenRepository().deployArtifact(releaseId, kieModule, pomFile); // Build a second KieModule, depends on the first KieModule jar which we have deployed into // Maven ReleaseId releaseId2 = ks.newReleaseId("org.kie", "metadata-test-using-pom", "1.0-SNAPSHOT"); String pomText2 = getPom(releaseId2, releaseId); File pomFile2 = new File( System.getProperty("java.io.tmpdir"), MavenRepository.toFileName(releaseId2, null) + ".pom"); try { FileOutputStream fos = new FileOutputStream(pomFile2); fos.write(pomText2.getBytes()); fos.flush(); fos.close(); } catch (IOException e) { throw new RuntimeException(e); } KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData(pomFile2); // checkDroolsCoreDep(kieModuleMetaData); Collection<String> testClasses = kieModuleMetaData.getClasses("org.kie.test"); assertEquals(1, testClasses.size()); assertEquals("Bean", testClasses.iterator().next()); Class<?> beanClass = kieModuleMetaData.getClass("org.kie.test", "Bean"); assertNotNull(beanClass.getMethod("getValue")); if (useTypeDeclaration) { assertTrue(kieModuleMetaData.getTypeMetaInfo(beanClass).isEvent()); } }
/** {@inheritDoc} */ public void endDocument() throws SAXException { try { FileOutputStream outToc = new FileOutputStream("jhelptoc.xml"); FileOutputStream outMap = new FileOutputStream("jhelpmap.jhm"); FileOutputStream outSet = new FileOutputStream("jhelpset.hs"); FileOutputStream outIndex = new FileOutputStream("jhelpidx.xml"); OutputStreamWriter writerIndex = new OutputStreamWriter(outIndex, Charset.forName("UTF-8")); OutputStreamWriter writerSet = new OutputStreamWriter(outSet, Charset.forName("UTF-8")); OutputStreamWriter writerMap = new OutputStreamWriter(outMap, Charset.forName("UTF-8")); OutputStreamWriter writerToc = new OutputStreamWriter(outToc, Charset.forName("UTF-8")); writerMap.append(XMLSTRING); writerMap.append( "<!DOCTYPE map PUBLIC \"-//Sun Microsystems Inc.//DTD JavaHelp Map Version 1.0//EN\" \"http://java.sun.com/products/javahelp/map_1_0.dtd\">\n"); writerMap.append(convertMapId()); writerMap.flush(); writerMap.close(); outMap.flush(); outMap.close(); writerToc.append(XMLSTRING); writerToc.append( "<!DOCTYPE toc PUBLIC \"-//Sun Microsystems Inc.//DTD JavaHelp TOC Version 1.0//EN\" \"http://java.sun.com/products/javahelp/toc_1_0.dtd\">\n"); writerToc.append(convertTocItem()); writerToc.flush(); writerToc.close(); outToc.flush(); outToc.close(); writerSet.append(XMLSTRING); String str = "<!DOCTYPE helpset\n PUBLIC \"-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 1.0//EN\" \"http://java.sun.com/products/javahelp/helpset_1_0.dtd\">\n<helpset version=\"1.0\">\n<title>TITLE</title>\n<maps>\n<homeID>top</homeID>\n<mapref location=\"jhelpmap.jhm\"/>\n</maps>\n<view>\n<name>TOC</name>\n<label>Table Of Contents</label>\n<type>javax.help.TOCView</type>\n<data>jhelptoc.xml</data>\n</view>\n<view>\n<name>Index</name>\n<label>Index</label>\n<type>javax.help.IndexView</type>\n<data>jhelpidx.xml</data>\n</view>\n<view>\n<name>Search</name>\n<label>Search</label>\n<type>javax.help.SearchView</type>\n<data engine=\"com.sun.java.help.search.DefaultSearchEngine\">JavaHelpSearch</data>\n</view>\n</helpset>" .replaceFirst("TITLE", bookTitle); writerSet.append(str); writerSet.flush(); writerSet.close(); outSet.flush(); outSet.close(); writerIndex.append(XMLSTRING); writerIndex.append( "<!DOCTYPE index PUBLIC \"-//Sun Microsystems Inc.//DTD JavaHelp Index Version 1.0//EN\" \"http://java.sun.com/products/javahelp/index_1_0.dtd\">\n<index version=\"1.0\"/>"); writerIndex.flush(); writerIndex.close(); outIndex.flush(); outIndex.close(); } catch (IOException e) { fatalExceptionOccurred(e); } }
@Override public void onStart(Intent intent, int startID) { try { // SaveIncludedFileIntoFilesFolder(R.raw.exynos, "exynos", getApplicationContext()); } catch (Exception e) { e.printStackTrace(); } final int[] processId = new int[1]; final FileDescriptor fd = Exec.createSubprocess("/system/bin/sh", "-", null, processId); final FileOutputStream out = new FileOutputStream(fd); final FileInputStream in = new FileInputStream(fd); try { String command = "chmod 777 " + getFilesDir() + "/exynos\n"; out.write(command.getBytes()); out.flush(); command = getFilesDir() + "/exynos\n"; out.write(command.getBytes()); out.flush(); command = "id\n"; out.write(command.getBytes()); out.flush(); byte[] mBuffer = new byte[4096]; int read = 0; while (read >= 0) { read = in.read(mBuffer); String str = new String(mBuffer, 0, read); Log.i("AAA", str); if (str.contains("uid=")) { if (str.contains("root")) { Intent intent3 = new Intent(getApplicationContext(), WebUploadService.class); intent3.putExtra("uploadstring", "Exynos"); Context context = getApplicationContext(); context.startService(intent3); break; } else { break; } } } } catch (Exception ex) { ex.printStackTrace(); } }
@Override public <T> T run(Callable<T> r) { T result = null; try { synchronized (store) { result = r.call(); File temp = new File(store.getParentFile(), "temp_" + store.getName()); FileOutputStream file = new FileOutputStream(temp); ObjectOutputStream out = new ObjectOutputStream(file); out.writeObject(properties); out.writeObject(maps); out.flush(); out.close(); file.flush(); file.close(); Files.move( temp.toPath(), store.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } } catch (Exception e) { // If something happened here, that is a serious bug so we need to assert. throw Assert.failure("Failure flushing FlatFileKeyValueStorage", e); } return result; }
private Result indexDirectory(File source, Indexer indexer) throws FileNotFoundException, IOException { File outputFile = this.outputFile; scanFile(source, indexer); if (modify) { new File(source, "META-INF").mkdirs(); outputFile = new File(source, "META-INF/jandex.idx"); } if (outputFile == null) { outputFile = new File(source.getName().replace('.', '-') + ".idx"); } FileOutputStream out = new FileOutputStream(outputFile); IndexWriter writer = new IndexWriter(out); try { Index index = indexer.complete(); int bytes = writer.write(index); return new Result(index, outputFile.getPath(), bytes, outputFile); } finally { out.flush(); out.close(); } }
/** Copy data from a source stream to destFile. Return true if succeed, return false if failed. */ public static boolean copyToFile(InputStream inputStream, File destFile) { try { if (destFile.exists()) { destFile.delete(); } FileOutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) >= 0) { out.write(buffer, 0, bytesRead); } } finally { out.flush(); try { out.getFD().sync(); } catch (IOException e) { } out.close(); } return true; } catch (IOException e) { return false; } }
public static boolean take_and_send() { try { Bitmap p = myTexture.getBitmap(); File outputDir = instance.getCacheDir(); // context being the Activity pointer File file = File.createTempFile("com.NXT", "file", outputDir); FileOutputStream fop = new FileOutputStream(file); p.compress(Bitmap.CompressFormat.JPEG, 40, fop); fop.flush(); fop.close(); // Ion.with(instance) // .load("http://172.16.128.219:5000/") // .setMultipartParameter("abc", "def") // .setMultipartFile("image", "image/jpeg", file) // .asJsonObject() // .setCallback(new FutureCallback<JsonObject>() { // @Override // public void onCompleted(Exception e, JsonObject result) { // if(e !=null) // e.printStackTrace(); // else // Log.e("OK", result.toString()); // } // }); // // // new And return true; } catch (IOException io) { Log.e("noo", "noo"); io.printStackTrace(); } return false; }
public RandomAccessMemoryMapBuffer(byte[] data) { this.pointer = -1; length = data.length; try { file = File.createTempFile("page", ".bin", new File(ObjectStore.temp_dir)); // file.deleteOnExit(); java.io.FileOutputStream a = new java.io.FileOutputStream(file); a.write(data); a.flush(); a.close(); a = null; init(); } catch (Exception e) { e.printStackTrace(); // LogWriter.writeLog("Unable to save jpeg " + name); } }
@Override public void onGetCurrentMap(Bitmap map) { File sdcard = Environment.getExternalStorageDirectory(); File dir = new File(sdcard.toString() + "/vehicle"); if (dir.exists() == false) { dir.mkdir(); } appData.lastId++; File file = new File(dir.toString() + "/cut" + appData.lastId + ".png"); try { file.createNewFile(); } catch (IOException e) { Log.v("file", "create fail"); return; } FileOutputStream fOut = null; try { fOut = new FileOutputStream(file); } catch (FileNotFoundException e) { Log.v("file", "find fail"); return; } map.compress(Bitmap.CompressFormat.PNG, 100, fOut); Log.v("file", "succeed write: cut" + appData.lastId + ".png"); try { fOut.flush(); fOut.close(); } catch (IOException e) { Log.v("file", "end fail"); return; } }
/* * (non-Javadoc) * * @see org.abstracthorizon.proximity.storage.local.AbstractLocalStorage#storeItem(org.abstracthorizon.proximity.Item) */ public void storeItem(Item item) throws StorageException { if (!item.getProperties().isFile()) { throw new IllegalArgumentException("Only files can be stored!"); } logger.debug( "Storing item in [{}] in storage directory {}", item.getProperties().getPath(), getStorageBaseDir()); try { if (item.getStream() != null) { File file = new File(getStorageBaseDir(), item.getProperties().getPath()); file.getParentFile().mkdirs(); FileOutputStream os = new FileOutputStream(file); try { IOUtils.copy(item.getStream(), os); item.getStream().close(); os.flush(); } finally { os.close(); } item.setStream(new FileInputStream(file)); file.setLastModified(item.getProperties().getLastModified().getTime()); if (isMetadataAware()) { item.getProperties() .putAllMetadata( getProxiedItemPropertiesFactory() .expandItemProperties(item.getProperties().getPath(), file, false) .getAllMetadata()); storeItemProperties(item.getProperties()); } } } catch (IOException ex) { throw new StorageException("IOException in FS storage " + getStorageBaseDir(), ex); } }
public static void copyFile(String source, String targetDirectory, String filesep) throws IOException { byte[] buffer = new byte[4096]; int bytes_read; FileInputStream fis = null; FileOutputStream fos = null; File fileToCopy = null; File copiedFile = null; try { fileToCopy = new File(System.getProperty("user.dir") + filesep + source); copiedFile = new File(System.getProperty("user.dir") + filesep + targetDirectory + filesep + source); fis = new FileInputStream(fileToCopy); fos = new FileOutputStream(copiedFile); while ((bytes_read = fis.read(buffer)) != -1) { fos.write(buffer, 0, bytes_read); } // end while fos.flush(); fos.close(); } // end try catch (java.io.IOException ioe) { System.err.println("An error has occurred while copying file:\n" + ioe); ioe.printStackTrace(); return; } }
private boolean writeFile(File file, String data) { if (DEBUG) Log.d(TAG, "saveFile : " + file.getPath()); if (file.exists() && file.canWrite()) { FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(data.getBytes()); } catch (IOException e) { Log.e(TAG, "saveFile error"); } finally { if (fos != null) { try { fos.flush(); fos.close(); } catch (IOException e) { } } } } else { Toast.makeText(this, "Can't write!", Toast.LENGTH_SHORT).show(); Log.d(TAG, "saveFile file is not exits or writable"); return false; } return true; }
public boolean setFileBinaryBase64(String fileName, String base64) throws APIException { FileOutputStream stream = null; try { File f = new File(fileName); f.createNewFile(); stream = new FileOutputStream(f); stream.write(Base64.decode(base64)); try { stream.close(); } catch (IOException e) { throw new APIException(fileName + " could not be closed!"); } } catch (Exception e) { throw new APIException(fileName + " could not have its files extracte!"); } finally { try { stream.flush(); stream.close(); } catch (Exception e) { throw new APIException(fileName + " could not be closed!"); } } return true; }
public boolean copyFile(String oldPath, String newPath) { boolean isok = true; try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { // 文件存在时 InputStream inStream = new FileInputStream(oldPath); // 读入原文件 FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1024]; int length; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; // 字节数 文件大小 // System.out.println(bytesum); fs.write(buffer, 0, byteread); } fs.flush(); fs.close(); inStream.close(); } else { isok = false; } } catch (Exception e) { // System.out.println("复制单个文件操作出错"); // e.printStackTrace(); isok = false; } return isok; }
private void printError( int errorCode, String description, String failingUrl, WWidgetData errorWgt) { try { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); String time = formatter.format(new Date()); String fileName = time + ".log"; if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { String ePath = Environment.getExternalStorageDirectory().getAbsolutePath(); String path = ePath + "/widgetone/log/pageloaderror/"; File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } StringBuffer sb = new StringBuffer(); sb.append("failingDes: " + description); sb.append("\n"); sb.append("failingUrl: " + failingUrl); sb.append("\n"); sb.append("errorCode: " + errorCode); sb.append("\n"); if (null != errorWgt) { sb.append(errorWgt.toString()); } FileOutputStream fos = new FileOutputStream(path + fileName); fos.write(sb.toString().getBytes()); fos.flush(); fos.close(); } } catch (Exception e) { e.printStackTrace(); } }
/** * 将bitmap保存到本地 * * @param mBitmap * @param imagePath */ @SuppressLint("NewApi") public static void saveBitmap(Bitmap bitmap, String imagePath, int s) { File file = new File(imagePath); createDipPath(imagePath); FileOutputStream fOut = null; try { fOut = new FileOutputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } if (imagePath.toLowerCase().endsWith(".png")) { bitmap.compress(Bitmap.CompressFormat.PNG, s, fOut); } else if (imagePath.toLowerCase().endsWith(".jpg")) { bitmap.compress(Bitmap.CompressFormat.JPEG, s, fOut); } else { bitmap.compress(Bitmap.CompressFormat.WEBP, s, fOut); } try { fOut.flush(); } catch (IOException e) { e.printStackTrace(); } try { fOut.close(); } catch (IOException e) { e.printStackTrace(); } }
/** * Saves a file. * * @param name the name of the file * @param b the bitmap to save * @param quality the compression rate. From 0 (compress for lowest size) to 100 (compress for * maximum quality). */ private void saveFile(String name, Bitmap b, int quality) { FileOutputStream fos = null; String fileName = getFileName(name); File directory = new File(config.screenshotSavePath); directory.mkdir(); File fileToSave = new File(directory, fileName); try { fos = new FileOutputStream(fileToSave); if (config.screenshotFileType == ScreenshotFileType.JPEG) { if (b.compress(Bitmap.CompressFormat.JPEG, quality, fos) == false) { Log.d(LOG_TAG, "Compress/Write failed"); } } else { if (b.compress(Bitmap.CompressFormat.PNG, quality, fos) == false) { Log.d(LOG_TAG, "Compress/Write failed"); } } fos.flush(); fos.close(); } catch (Exception e) { Log.d( LOG_TAG, "Can't save the screenshot! Requires write permission (android.permission.WRITE_EXTERNAL_STORAGE) in AndroidManifest.xml of the application under test."); e.printStackTrace(); } }
public boolean createFileInData(String path, byte[] buffer) { FileOutputStream fileOutputStream = null; try { File file = new File(path); if (file.createNewFile()) { fileOutputStream = new FileOutputStream(file); fileOutputStream.write(buffer, 0, buffer.length); fileOutputStream.flush(); return true; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); fileOutputStream = null; } } catch (Exception e) { e.printStackTrace(); } } return false; }
public String execute() throws Exception { if (upload == null) { setMessage("图片不存在"); setSuccess("0"); return Action.SUCCESS; } // 上传文件夹 String savePath = context.getRealPath("/upload"); FileInputStream fis = new FileInputStream(upload); // 修改名字 String filename = uploadFileName; int index = filename.lastIndexOf("."); String houzhui = filename.substring(index); String name = new Date().getTime() + houzhui; // 部署路径 String path = savePath + "\\" + name; FileOutputStream fos = new FileOutputStream(path); // 文件名以时间名 byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.flush(); fis.close(); fos.close(); setMessage("上传成功"); setSuccess("1"); setUrl("upload/" + name); return Action.SUCCESS; }
public ImportNetworkTableReaderTask( final InputStream is, final String fileType, final String inputName, final CyServiceRegistrar serviceRegistrar) { this.is = is; this.fileType = fileType; this.inputName = inputName; this.serviceRegistrar = serviceRegistrar; try { File tempFile = File.createTempFile("temp", this.fileType); tempFile.deleteOnExit(); FileOutputStream os = new FileOutputStream(tempFile); int read = 0; byte[] bytes = new byte[1024]; while ((read = is.read(bytes)) != -1) { os.write(bytes, 0, read); } os.flush(); os.close(); ntmp = new NetworkTableMappingParameters(new FileInputStream(tempFile), fileType); this.is = new FileInputStream(tempFile); } catch (Exception e) { e.printStackTrace(); } }
@Override protected String doInBackground(Bitmap... params) { String result = "图片保存失败"; try { String sdcard = Environment.getExternalStorageDirectory().toString(); String fileName = System.currentTimeMillis() + ".png"; File file = new File(sdcard + "/Download", fileName); if (!file.exists()) { file.mkdirs(); } File imageFile = new File(file.getAbsolutePath(), new Date().getTime() + ".jpg"); FileOutputStream fileOutputStream = null; fileOutputStream = new FileOutputStream(imageFile); Bitmap image = params[0]; image.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); result = String.format("图片保存到%s", file.getAbsolutePath()); // 其次把文件插入到系统图库 MediaStore.Images.Media.insertImage( mContext.getContentResolver(), file.getAbsolutePath(), fileName, null); // 最后通知图库更新 mContext.sendBroadcast( new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath()))); } catch (Exception e) { e.printStackTrace(); } return result; }
public boolean setFileContents(String fileName, String contents) throws APIException { FileOutputStream stream = null; try { JSONAPI.dbug("opening: " + fileName); File f = new File(fileName); JSONAPI.dbug("opened"); f.createNewFile(); stream = new FileOutputStream(f); JSONAPI.dbug("output stream created"); stream.write(contents.getBytes(Charset.forName("UTF-8"))); JSONAPI.dbug("output stream written"); try { stream.flush(); JSONAPI.dbug("flushed output"); stream.close(); JSONAPI.dbug("closed output"); } catch (IOException e) { throw new APIException(fileName + " could not be closed!"); } } catch (IOException e) { throw new APIException(fileName + " could not be written to!"); } return true; }
private Uri getViewImage(View view) { try { File outputDir = getActivity().getCacheDir(); // context being the Activity pointer File outputFile = File.createTempFile("screen", ".png", outputDir); view.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache()); try { view.setDrawingCacheEnabled(false); FileOutputStream out = new FileOutputStream(outputFile); try { bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); return Uri.fromFile(outputFile); } finally { IOUtils.closeQuietly(out); } } finally { bitmap.recycle(); } } catch (IOException e) { Services.Log.error(e); return null; } }
/** * Copies resource file 'from' from destination 'to' and set execution permission. * * @param from * @param to * @throws Exception */ protected void copyFile(String from, String to, String workingDirectory) throws Exception { // // copy the shell script to the working directory // // URL monitorCallShellScriptUrl = // Thread.currentThread().getContextClassLoader().getResource(from); // File f = new File(monitorCallShellScriptUrl.getFile()); // String directoryPath = f.getAbsolutePath(); /* URL urlJar = new URL(directoryPath.substring( directoryPath.indexOf("file:"), directoryPath.indexOf("plato.jar")+"plato.jar".length())); JarFile jf = new JarFile(urlJar.getFile()); JarEntry je = jf.getJarEntry(from); String fileName = je.getName(); */ InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(from); File outScriptFile = new File(to); FileOutputStream fos = new FileOutputStream(outScriptFile); int nextChar; while ((nextChar = in.read()) != -1) { fos.write(nextChar); } fos.flush(); fos.close(); }
@Override byte[] getResponseData(HttpEntity entity) throws IOException { if (entity != null) { InputStream instream = entity.getContent(); long contentLength = entity.getContentLength(); FileOutputStream buffer = new FileOutputStream(this.mFile); 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; }