/** Writes the chunks to a file as a contiguous stream. Useful for debugging. */ public void saveToFile(File file) { Log.d(TAG, "saving chunk data to file " + file); FileOutputStream fos = null; BufferedOutputStream bos = null; try { fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); fos = null; // closing bos will also close fos int numChunks = getNumChunks(); for (int i = 0; i < numChunks; i++) { byte[] chunk = mChunks.get(i); bos.write(chunk); } } catch (IOException ioe) { throw new RuntimeException(ioe); } finally { try { if (bos != null) { bos.close(); } if (fos != null) { fos.close(); } } catch (IOException ioe) { throw new RuntimeException(ioe); } } }
public static void writeObject(Context context, String key, Object object) throws IOException { FileOutputStream fos = context.openFileOutput(key, Context.MODE_PRIVATE); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(object); oos.close(); fos.close(); }
private static void testSysOut(String fs, String exp, Object... args) { FileOutputStream fos = null; FileInputStream fis = null; try { PrintStream saveOut = System.out; fos = new FileOutputStream("testSysOut"); System.setOut(new PrintStream(fos)); System.out.format(Locale.US, fs, args); fos.close(); fis = new FileInputStream("testSysOut"); byte[] ba = new byte[exp.length()]; int len = fis.read(ba); String got = new String(ba); if (len != ba.length) fail(fs, exp, got); ck(fs, exp, got); System.setOut(saveOut); } catch (FileNotFoundException ex) { fail(fs, ex.getClass()); } catch (IOException ex) { fail(fs, ex.getClass()); } finally { try { if (fos != null) fos.close(); if (fis != null) fis.close(); } catch (IOException ex) { fail(fs, ex.getClass()); } } }
/** * Helper method to get the contents of the visitor message, save the image, and save the event * * @param msg */ private void saveVisitor(StateDeviceProtos.StateDeviceMessage msg) { Log.i(TAG, "Logging Event"); Visitor visitor = new Visitor(); Long time = System.currentTimeMillis(); ByteString data = msg.getData(); String filename = "visitor" + System.currentTimeMillis() + ".jpg"; visitor.setImagePath(filename); File imageDirectory = new File(mContext.getFilesDir() + ConstantManager.IMAGE_DIR); // create the image directory if it doesn't exist if (!imageDirectory.exists()) { Log.i(TAG, "Directory being created? " + imageDirectory.mkdirs()); } // save the image file File image = new File(imageDirectory, filename); try { if (!image.exists()) { Log.i(TAG, "File being created? " + image.createNewFile()); } FileOutputStream fos = new FileOutputStream(image, true); fos.write(data.toByteArray()); fos.close(); } catch (IOException e) { e.printStackTrace(); } // Log the visitor visitor.setTime(time); visitor.setLocation(msg.getName()); VisitorLog.logVisitor(visitor, mContext); }
public synchronized ClassLoader getClassLoader(ProcessDefinition def) throws IOException { ClassLoader cl = cache.get(def.getId()); if (cl == null) { File pdCache = new File(cacheRoot, Long.toString(def.getId())); if (!pdCache.exists()) { FileDefinition fd = def.getFileDefinition(); for (Map.Entry<String, byte[]> entry : ((Map<String, byte[]>) fd.getBytesMap()).entrySet()) { File f = new File(pdCache, entry.getKey()); f.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(f); IOUtils.copy(new ByteArrayInputStream(entry.getValue()), fos); fos.close(); } } cl = new URLClassLoader( new URL[] {new URL(pdCache.toURI().toURL(), "classes/")}, Hudson.getInstance().getPluginManager().uberClassLoader) { @Override public Class<?> loadClass(String name) throws ClassNotFoundException { System.out.println(name); return super.loadClass(name); } }; cache.put(def.getId(), cl); } return cl; }
public void run() { try { done = false; final String PATH = "/home/lvuser/AutoRoutineData.ser"; File file = new File(PATH); if (!file.exists()) { file.createNewFile(); } else { file.delete(); file.createNewFile(); } FileOutputStream fileOut = new FileOutputStream(file); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(data); out.close(); fileOut.close(); Repository.Log.info("Serialized auto routine data: " + data.toString()); done = true; } catch (Exception ex) { Repository.Logs.error("Failed to serialize auto routine data", ex); done = true; } }
void serialize(File f) throws IOException { FileOutputStream fos = new FileOutputStream(f); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(this); oos.close(); fos.close(); }
public boolean createJar(File jarFilename, File... filesToAdd) { try { FileOutputStream stream = new FileOutputStream(jarFilename); JarOutputStream out = new JarOutputStream(stream, new Manifest()); BufferedOutputStream bos = new BufferedOutputStream(out); for (File fileToAdd : filesToAdd) { if (fileToAdd == null || !fileToAdd.exists() || fileToAdd.isDirectory()) { continue; // Just in case... } JarEntry jarAdd = new JarEntry(fileToAdd.getName()); jarAdd.setTime(fileToAdd.lastModified()); out.putNextEntry(jarAdd); FileInputStream in = new FileInputStream(fileToAdd); BufferedInputStream bis = new BufferedInputStream(in); int data; while ((data = bis.read()) != -1) { bos.write(data); } bis.close(); in.close(); } bos.close(); out.close(); stream.close(); } catch (FileNotFoundException e) { // skip not found file } catch (IOException e) { e.printStackTrace(); } return true; }
private void writeAudioDataToFile() { byte data[] = new byte[bufferSize]; String filename = getTempFilename(); FileOutputStream os = null; try { os = new FileOutputStream(filename); } catch (FileNotFoundException e) { // TODO Auto-generated catch block Log.d("SAN", e.getMessage()); } int read = 0; if (null != os) { while (isRecording) { read = recorder.read(data, 0, bufferSize); if (AudioRecord.ERROR_INVALID_OPERATION != read) { try { os.write(data); } catch (IOException e) { Log.d("SAN", e.getMessage()); } } } try { os.close(); } catch (IOException e) { Log.d("SAN", e.getMessage()); } } }
@Before public void setUp() throws Exception { // Download file for test URL website = new URL("http://archive.org/web/images/logo_wayback_210x77.png"); ReadableByteChannel resFile = Channels.newChannel(website.openStream()); // Create file File file = new File(pathTempFile); FileOutputStream fos = new FileOutputStream(pathTempFile); fos.getChannel().transferFrom(resFile, 0, Long.MAX_VALUE); // Save to MultipartFile FileInputStream input = new FileInputStream(file); multipartFile = new MockMultipartFile("file", file.getName(), "image/png", IOUtils.toByteArray(input)); fos.close(); input.close(); // Set paths attachmentService.setStoragePath(storagePath); attachmentService.setPathDefaultPreview(pathDefaultPreview); }
private void doTasksExport(String output) throws IOException { File xmlFile = new File(output); xmlFile.createNewFile(); FileOutputStream fos = new FileOutputStream(xmlFile); xml = Xml.newSerializer(); xml.setOutput(fos, BackupConstants.XML_ENCODING); xml.startDocument(null, null); xml.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); xml.startTag(null, BackupConstants.ASTRID_TAG); xml.attribute( null, BackupConstants.ASTRID_ATTR_VERSION, Integer.toString(preferences.getLastSetVersion())); xml.attribute(null, BackupConstants.ASTRID_ATTR_FORMAT, Integer.toString(FORMAT)); serializeTasks(); serializeTagDatas(); xml.endTag(null, BackupConstants.ASTRID_TAG); xml.endDocument(); xml.flush(); fos.close(); }
public boolean Write(byte[] buffer) { try { if (mFileOutputStream == null) { return false; } int sendSize = 100; if (buffer.length <= sendSize) { mFileOutputStream.write(buffer); return true; } for (int j = 0; j < buffer.length; j += sendSize) { byte[] btPackage = new byte[sendSize]; if (buffer.length - j < sendSize) { btPackage = new byte[buffer.length - j]; } System.arraycopy(buffer, j, btPackage, 0, btPackage.length); mFileOutputStream.write(btPackage); Thread.sleep(10); } } catch (IOException e) { Log.e(TAG, e.getMessage()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; }
/** * Writes data out in XML format. * * @return A flag indicating the success of the operation. */ private boolean writeXMLFile() { File selectedFile = model.getFile(); try { FileOutputStream ow = new FileOutputStream(selectedFile); DriveTrainEncoder.encode(ow, model); ow.close(); model.reset(); return true; } catch (IOException iox) { JOptionPane.showMessageDialog( this, Messages.format("Main.15", iox.getLocalizedMessage()), // $NON-NLS-1$ Messages.getString("Main.16"), JOptionPane.ERROR_MESSAGE); // $NON-NLS-1$ return false; } catch (ParserConfigurationException iox) { JOptionPane.showMessageDialog( this, Messages.format("ParserConfigurationException", iox.getLocalizedMessage()), // $NON-NLS-1$ Messages.getString("Main.16"), JOptionPane.ERROR_MESSAGE); // $NON-NLS-1$ return false; } catch (TransformerException iox) { JOptionPane.showMessageDialog( this, Messages.format("TransformerException", iox.getLocalizedMessage()), // $NON-NLS-1$ Messages.getString("Main.16"), JOptionPane.ERROR_MESSAGE); // $NON-NLS-1$ return false; } }
private void saveSpecifiedPorts() { String filename; String javaHome = System.getProperty("java.home"); String pathSep = System.getProperty("path.separator", ":"); String fileSep = System.getProperty("file.separator", "/"); String lineSep = System.getProperty("line.separator"); String output; if (PortType == PORT_SERIAL) { filename = javaHome + fileSep + "lib" + fileSep + "gnu.io.rxtx.SerialPorts"; } else if (PortType == PORT_PARALLEL) { filename = javaHome + "gnu.io.rxtx.ParallelPorts"; } else { System.out.println("Bad Port Type!"); return; } System.out.println(filename); try { FileOutputStream out = new FileOutputStream(filename); for (int i = 0; i < 128; i++) { if (cb[i].getState()) { output = cb[i].getLabel() + pathSep; out.write(output.getBytes()); } } out.write(lineSep.getBytes()); out.close(); } catch (IOException e) { System.out.println("IOException!"); } }
public void saveToFile(String filename) throws IOException { FileOutputStream stream = new FileOutputStream(filename); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream)); String nl = "\r\n"; writer.write(numVertices + " " + numEdges + nl); for (int i = 0; i < numVertices; ++i) { Vertex vertex = vertices.get(i); writer.write(vertex.data.x + " " + vertex.data.y + nl); } if (numEdges > 0) { for (int i = 0; i < numVertices; ++i) { Vertex vertex = vertices.get(i); ArrayList<Vertex> adjList = vertex.adjacencyList; for (int j = 0; j < adjList.size(); ++j) { writer.write(adjList.get(j).id + " "); } writer.write(nl); } } writer.flush(); writer.close(); stream.close(); }
/** @since 3.0 */ @Override public void setTimestampTransform(final ITmfTimestampTransform tt) { fTsTransform = tt; /* Save the timestamp transform to a file */ File sync_file = getSyncFormulaFile(); if (sync_file != null) { if (sync_file.exists()) { sync_file.delete(); } FileOutputStream fos; ObjectOutputStream oos; /* Save the header of the file */ try { fos = new FileOutputStream(sync_file, false); oos = new ObjectOutputStream(fos); oos.writeObject(fTsTransform); oos.close(); fos.close(); } catch (IOException e1) { Activator.logError("Error writing timestamp transform for trace", e1); // $NON-NLS-1$ } } }
/** * Download files from url by the stream used in DownloadDataStreamService silently return if * something goes wrong */ public static String downloadUsingStream( Context context, String urlStr, String fileType, String fileId) { Log.d( TAG, "downloadUsingStream()" + "; id=" + fileId + ", type=" + fileType + ", url=" + urlStr); String result = ""; try { // Note that if external storage is not currently mounted this will silently fail. File storageDir = context.getExternalFilesDir(fileType); // define file name with extention out from fileType String fileName = fileId + (fileType == Utils.TYPE_PICTURE ? ".jpg" : ".html"); File file = new File(storageDir, fileName); URL url = new URL(urlStr); BufferedInputStream bis = new BufferedInputStream(url.openStream()); FileOutputStream fis = new FileOutputStream(file); byte[] buffer = new byte[Utils.BUFFER_SIZE]; int count = 0; while ((count = bis.read(buffer, 0, Utils.BUFFER_SIZE)) != -1) fis.write(buffer, 0, count); fis.close(); bis.close(); result = file.getAbsolutePath(); } catch (IOException ex) { Log.e(TAG, ".onHandleIntent(); Error downloadUsingStream(), url=" + urlStr, ex); } // return path to downloaded file return result; }
public void kopi(String sumber, String sasaran) throws IOException { FileInputStream masukan = null; FileOutputStream keluaran = null; BufferedInputStream masukanBuffer = null; BufferedOutputStream keluaranBuffer = null; try { masukan = new FileInputStream(sumber); masukanBuffer = new BufferedInputStream(masukan); keluaran = new FileOutputStream(sasaran); keluaranBuffer = new BufferedOutputStream(keluaran); int karakter = masukanBuffer.read(); while (karakter != -1) { keluaranBuffer.write(karakter); karakter = masukanBuffer.read(); } keluaranBuffer.flush(); } finally { if (masukan != null) masukan.close(); if (masukanBuffer != null) masukanBuffer.close(); if (keluaran != null) keluaran.close(); if (keluaranBuffer != null) { keluaranBuffer.close(); } } }
/** * <根据URL下载图片,并保存到本地> <功能详细描述> * * @param imageURL * @param context * @return * @see [类、类#方法、类#成员] */ public static Bitmap loadImageFromUrl(String imageURL, File file, Context context) { Bitmap bitmap = null; try { URL url = new URL(imageURL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoInput(true); con.connect(); if (con.getResponseCode() == 200) { InputStream inputStream = con.getInputStream(); FileUtil.deleteDirectory(FileSystemManager.getUserHeadPath(context, Global.getUserId())); ByteArrayOutputStream OutputStream = new ByteArrayOutputStream(); FileOutputStream out = new FileOutputStream(file.getPath()); byte buf[] = new byte[1024 * 20]; int len = 0; while ((len = inputStream.read(buf)) != -1) { OutputStream.write(buf, 0, len); } OutputStream.flush(); OutputStream.close(); inputStream.close(); out.write(OutputStream.toByteArray()); out.close(); BitmapFactory.Options imageOptions = new BitmapFactory.Options(); imageOptions.inPreferredConfig = Bitmap.Config.RGB_565; imageOptions.inPurgeable = true; imageOptions.inInputShareable = true; bitmap = BitmapFactory.decodeFile(file.getPath(), imageOptions); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap; }
private void saveSettings() { if (settings == null) return; File fSettings = new File(getDataFolder(), "settings.npr"); try { getDataFolder().mkdirs(); } catch (Exception e) { return; } FileOutputStream fOut = null; ObjectOutputStream out = null; try { fOut = new FileOutputStream(fSettings); out = new ObjectOutputStream(fOut); out.writeObject(settings); } catch (Exception e) { } finally { try { if (fOut != null) fOut.close(); if (out != null) out.close(); } catch (Exception e) { } } }
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; }
public static SQLiteDatabase OpenDataBase(Context mContext, String dbName, String assertDBName) { File dataFolder = mContext.getFilesDir(); File dbFile = new File(dataFolder.getAbsolutePath() + "/" + dbName); Log.v("DataCenter", dbFile.getAbsolutePath()); if (!dbFile.exists()) { try { InputStream inputStream = mContext.getAssets().open(assertDBName); FileOutputStream fso = new FileOutputStream(dbFile); byte[] buffer = new byte[1024]; int readCount = 0; while ((readCount = inputStream.read(buffer)) > 0) { fso.write(buffer); } inputStream.close(); fso.close(); } catch (IOException e) { // TODO: handle exception e.printStackTrace(); } } SQLiteDatabase db = SQLiteDatabase.openDatabase( dbFile.getAbsolutePath(), null, SQLiteDatabase.CREATE_IF_NECESSARY); return db; }
private void copyWaveFile(String inFilename, String outFilename) { FileInputStream in = null; FileOutputStream out = null; long totalAudioLen = 0; long totalDataLen = totalAudioLen + 36; long longSampleRate = RECORDER_SAMPLERATE; int channels = 2; long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels / 8; byte[] data = new byte[bufferSize]; try { in = new FileInputStream(inFilename); out = new FileOutputStream(outFilename); totalAudioLen = in.getChannel().size(); totalDataLen = totalAudioLen + 36; // AppLog.logString("File size: " + totalDataLen); WriteWaveFileHeader(out, totalAudioLen, totalDataLen, longSampleRate, channels, byteRate); while (in.read(data) != -1) { out.write(data); } in.close(); out.close(); } catch (FileNotFoundException e) { Log.d("SAN", e.getMessage()); } catch (IOException e) { Log.d("SAN", e.getMessage()); } }
/** * Internal copy file method. * * @param srcFile the validated source file, must not be <code>null</code> * @param destFile the validated destination file, must not be <code>null</code> * @throws IOException if an error occurs */ private static void doCopyFile(File srcFile, File destFile) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); } } finally { Streams.closeQuietly(output); Streams.closeQuietly(fos); Streams.closeQuietly(input); Streams.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { throw new IOException( "Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } }
/** * Save a stream to a file. * * <p>If the response could not be saved to the file due, for example, to a network error, the * file will not exist when this method returns. * * @param inputStream the stream whose content will be saved * @param targetFile the target file, which will be created if necessary * @return true if the operation was successful, false otherwise */ public static boolean saveToFile(final InputStream inputStream, final File targetFile) { if (inputStream == null) { return false; } try { try { final File tempFile = File.createTempFile("download", null, targetFile.getParentFile()); final FileOutputStream fos = new FileOutputStream(tempFile); final boolean written = copy(inputStream, fos); fos.close(); if (written) { return tempFile.renameTo(targetFile); } FileUtils.deleteIgnoringFailure(tempFile); return false; } finally { IOUtils.closeQuietly(inputStream); } } catch (final IOException e) { Log.e("LocalStorage.saveToFile", e); FileUtils.deleteIgnoringFailure(targetFile); } return false; }
public static File createBuildXML( String justepHome, String antLibDir, String nativeDir, AppInfo appInfo, String session) throws IOException, IllegalAccessException { File buildTmplFile = new File(antLibDir + "/build.xml"); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(buildTmplFile))); StringBuffer sb = new StringBuffer(); String str = null; while ((str = br.readLine()) != null) sb.append(str + "\r\n"); String content = sb.toString(); // 文件中的占位标识为@value@,和ant的文本替换一致 content = content.replace("@justepHome@", justepHome); content = content.replace("@antLibDir@", antLibDir); content = content.replace("@nativeDir@", nativeDir); content = content.replace("@session@", session); Class<? extends AppInfo> cls = appInfo.getClass(); Field[] flds = cls.getFields(); Object v; if (flds != null) { for (int i = 0; i < flds.length; i++) { v = flds[i].get(appInfo); content = content.replace("@" + flds[i].getName() + "@", v != null ? v.toString() : ""); } } File buildFile = File.createTempFile("x5app-build", ".xml"); buildFile.deleteOnExit(); FileOutputStream buildFileStream = new FileOutputStream(buildFile); buildFileStream.write(content.getBytes("UTF-8")); br.close(); buildFileStream.close(); return buildFile; }
/** * 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(); }
public void saveCard(String filePath, Card card) { File file = new File(filePath); if (!file.exists()) { try { file.createNewFile(); System.out.println("File " + file.getName() + " was created."); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { FileOutputStream fos = new FileOutputStream(filePath); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(card); fos.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } }
public static void downloadIt() { URL website; try { website = new URL(MainConstants.SOURCES_URL); try { InputStream in = new BufferedInputStream(website.openStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int n = 0; while (-1 != (n = in.read(buf))) { out.write(buf, 0, n); } out.close(); in.close(); byte[] response = out.toByteArray(); FileOutputStream fos = new FileOutputStream(MainConstants.INPUT_ZIP_FILE); fos.write(response); fos.close(); System.out.println("Download finished."); } catch (IOException ce) { System.out.print("Connection problem : " + ce); } } catch (MalformedURLException e) { e.printStackTrace(); } }
@Override public void creerCompte(Compte c) { // TODO File file = new File(fileName); FileOutputStream output = null; try { output = new FileOutputStream(file, true); Properties prop = new Properties(); String retour = ""; retour += "numero:" + c.getNumero() + "&intitulé:CC" + c.getIntitule() + "&solde:" + c.getSolde(); prop.setProperty(c.getNumero(), retour); // TODO découvert prop.store(output, null); } catch (IOException io) { io.printStackTrace(); } finally { if (output != null) { try { output.close(); } catch (IOException e) { e.printStackTrace(); } } } // TODO Auto-generated method stub }