/** * Returns true if the code was executed correctly. False if there was an error trying to share * the file. If the file was not supposed to be shared, and was not shared, true would still be * returned. */ private boolean shareTorrentFile(File torrentFile) { if (torrentManager.isDownloadingTorrent(torrentFile)) { return true; } if (!SharingSettings.SHARE_DOWNLOADED_FILES_IN_NON_SHARED_DIRECTORIES.getValue()) { return true; } BTData btData = null; FileInputStream torrentInputStream = null; try { torrentInputStream = new FileInputStream(torrentFile); Map<?, ?> torrentFileMap = (Map<?, ?>) Token.parse(torrentInputStream.getChannel()); btData = new BTDataImpl(torrentFileMap); } catch (IOException e) { LOG.error("Error reading torrent file: " + torrentFile, e); return false; } finally { FileUtils.close(torrentInputStream); } if (btData.isPrivate()) { gnutellaFileList.remove(torrentFile); return true; } File saveDir = SharingSettings.getSaveDirectory(); File torrentParent = torrentFile.getParentFile(); if (torrentParent.equals(saveDir)) { // already in saveDir gnutellaFileList.add(torrentFile); return true; } final File tFile = getSharedTorrentMetaDataFile(btData); if (tFile.equals(torrentFile)) { gnutellaFileList.add(tFile); return true; } gnutellaFileList.remove(tFile); File backup = null; if (tFile.exists()) { backup = new File(tFile.getParent(), tFile.getName().concat(".bak")); FileUtils.forceRename(tFile, backup); } if (FileUtils.copy(torrentFile, tFile)) { gnutellaFileList.add(tFile); } else { if (backup != null) { // restore backup if (FileUtils.forceRename(backup, tFile)) { gnutellaFileList.add(tFile); } } } return true; }
public void loadDump(File dumpFile, File lineFile, File dumpInfoFile) throws FileNotFoundException, IOException { FileInputStream vertexStream = new FileInputStream(dumpFile); MappedByteBuffer inVertex = vertexStream.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, dumpFile.length()); vertices = inVertex.asFloatBuffer(); FileInputStream vertexLineStream = new FileInputStream(lineFile); MappedByteBuffer inLine; inLine = vertexLineStream.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, lineFile.length()); stripVertexCounts = inLine.asIntBuffer(); Scanner scanner = new Scanner(dumpInfoFile); String line; line = scanner.nextLine(); minX = Float.parseFloat(line); line = scanner.nextLine(); maxX = Float.parseFloat(line); line = scanner.nextLine(); minY = Float.parseFloat(line); line = scanner.nextLine(); maxY = Float.parseFloat(line); }
/** * @param f * @param numPruebas * @throws FileNotFoundException * @throws IOException */ private static void prueba1(File f, int numPruebas) throws FileNotFoundException, IOException { FileInputStream fin; fin = new FileInputStream(f); // Open the file and then get a channel from the stream FileChannel channel = fin.getChannel(); int size = (int) channel.size(); // Get the file's size and then map it into memory ByteBuffer bbCorrect = channel.map(FileChannel.MapMode.READ_ONLY, 0, size); // Chunkeo a 1KB Random rnd = new Random(); long t1 = System.currentTimeMillis(); FileInputStream fin2 = new FileInputStream(f); FileChannel channel2 = fin2.getChannel(); BigByteBuffer bb = new BigByteBuffer(channel2, FileChannel.MapMode.READ_ONLY, 1024 * 1024); for (int i = 0; i < numPruebas; i++) { int pos = rnd.nextInt(size - 10); // pos = 2; byte bCorrect = bbCorrect.get(pos); byte bPrueba = bb.get(pos); if (bCorrect != bPrueba) { System.err.println("Error de lectura. " + bCorrect + " " + bPrueba); } else { // System.out.println("Correcto: pos=" + pos + " byte= " + bPrueba); } } close(channel2, fin2, bb); System.gc(); long t2 = System.currentTimeMillis(); System.out.println("T=" + (t2 - t1) + "mseconds"); }
public static void main(String[] args) throws IOException { System.out.println("PWD: " + System.getProperty("user.dir")); System.out.println("Input: " + args[0]); FileInputStream fis = new FileInputStream(new File(args[0])); System.out.println("input size: " + fis.getChannel().size()); PrintStructure ps = new PrintStructure(); ps.print(fis.getChannel(), 0, 0, 0); }
public static void initialize() throws IOException, ConfigurationException { try (FileInputStream fis = new FileInputStream("CHANGES.txt")) { dataSource = ByteBuffer.allocateDirect((int) fis.getChannel().size()); while (dataSource.hasRemaining()) { fis.getChannel().read(dataSource); } dataSource.flip(); } SchemaLoader.loadSchema(); SchemaLoader.schemaDefinition(""); }
public static void copyFile(@NotNull File from, @NotNull File to, boolean append) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { out = createOutputStream(to, append); in = new FileInputStream(from); FileChannel readChannel = in.getChannel(); FileChannel writeChannel = out.getChannel(); long size = readChannel.size(); for (long position = 0; position < size; ) { position += readChannel.transferTo(position, MB, writeChannel); } if (from.length() != to.length()) { throw new IOException("Failed to copy full contents from " + from + " to " + to); } } finally { close(in); close(out); } }
/** * @param startByte * @param endByte * @return * @throws Exception * @return true if all the bytes between in the file between startByte and endByte are null, false * otherwise */ private boolean isFilePortionNull(int startByte, int endByte) throws IOException { logger.config("Checking file portion:" + Hex.asHex(startByte) + ":" + Hex.asHex(endByte)); FileInputStream fis = null; FileChannel fc = null; try { fis = new FileInputStream(file); fc = fis.getChannel(); fc.position(startByte); ByteBuffer bb = ByteBuffer.allocateDirect(endByte - startByte); fc.read(bb); while (bb.hasRemaining()) { if (bb.get() != 0) { return false; } } } finally { if (fc != null) { fc.close(); } if (fis != null) { fis.close(); } } return true; }
/*Function to read file */ public byte[] getFile(String fname) throws Exception { /*FileInputStream and FileChannel for performance. */ FileInputStream in = new FileInputStream(fname); FileChannel ch = in.getChannel(); MappedByteBuffer mb = ch.map(FileChannel.MapMode.READ_ONLY, 0L, ch.size()); long l = (new File(fname)).length(); /*Currently, supported max size is 20MB*/ if (l > MAX_SIZE) { // errorMessage("File size too large. Max file size allowed // is"+(Integer.MAX_VALUE/1000)+"KB"); return null; } byte[] barray = new byte[(int) l]; int nGet; /*Read the file in to barray*/ while (mb.hasRemaining()) { nGet = Math.min(mb.remaining(), Integer.MAX_VALUE); mb.get(barray, 0, nGet); } if (in != null) in.close(); /*Return barray*/ return barray; }
public void bt_resetAction(View v) { // Log.d( SystemInfo.TIG, TAG + "::bt_resetAction() - RESET DATABASE" ); // TODO implement option to dump db data on SD card try { // TODO this code is not enough tested - it shall rather show the idea!!! File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath = "//data//" + SystemInfo.TIG + ".db" + "//databases//" + SystemInfo.DB_NAME; String backupDBPath = SystemInfo.DB_NAME; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); if (currentDB.exists()) { fileInputStream = new FileInputStream(currentDB); FileChannel src = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(backupDB); FileChannel dst = fileOutputStream.getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); } } } catch (Exception e) { Log.w(SystemInfo.TIG, TAG + " saving database failed"); } // reset DB (dialog) AlertDialog.Builder yesnobox = new AlertDialog.Builder(this); yesnobox.setMessage("Really remove all data?"); yesnobox.setTitle("Confirm Database Reset"); yesnobox.setPositiveButton( "Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { for (int idx = 0; idx < DB_list.size(); ++idx) { DB_list.get(idx).data_reset(); } // TODO rm /* DB.data_reset(); DB.data_reset(); // XXX DB.data_reset(); DB.data_reset(); //*/ // refresh to battery view displayData(SystemInfo.PLOT_BATTERY_COMMENT, SystemInfo.DB_TABLENAME_BATTERY); } }); yesnobox.setNegativeButton( "No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // do nothing ; } }); yesnobox.show(); }
public String getJsonFile() { String jString = null; try { File dir = Environment.getExternalStorageDirectory(); File yourFile = new File(dir, "form.json"); FileInputStream stream = new FileInputStream(yourFile); try { FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); /* Instead of using default, pass in a decoder. */ jString = Charset.defaultCharset().decode(bb).toString(); } finally { stream.close(); } jObject = new JSONObject(jString); } catch (Exception e) { e.printStackTrace(); } return jObject.toString(); }
/** * 根据文件名获取文件内容 * * @param file 文件 * @param charsetName 字符集 * @return 文件内容,UTF-8编码。不会为null,可为空字符串 */ public static String getFileContent(File file, String charsetName) { if (file.isFile()) { FileInputStream inf = null; FileChannel inc = null; StringBuilder content = new StringBuilder(); try { inf = new FileInputStream(file); inc = inf.getChannel(); Charset charset = Charset.forName(charsetName); CharsetDecoder decoder = charset.newDecoder(); InputStreamReader reader = new InputStreamReader(inf, decoder); char cbuf[] = new char[1024]; int count = 0; while ((count = reader.read(cbuf)) > -1) { content.append(cbuf, 0, count); } return content.toString(); } catch (UnmappableCharacterException e) { System.err.println( "The file's charset is not " + charsetName + ". file:" + file.getAbsolutePath()); // e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { close(inc); close(inf); } } else { // logger.warn("The file is not exists or is not a file!" + file.getAbsolutePath()); } return ""; }
public String getFileBinaryBase64(String fileName) throws APIException { if ((new File(fileName)).exists()) { FileInputStream stream = null; try { stream = new FileInputStream(new File(fileName)); FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); /* Instead of using default, pass in a decoder. */ byte[] b = new byte[bb.remaining()]; bb.get(b); return Base64.encodeBytes(b); } catch (Exception e) { throw new APIException(fileName + " could not have its files extracte!"); } finally { try { stream.close(); } catch (Exception e) { throw new APIException(fileName + " could not be closed!"); } } } else { throw new APIException(fileName + " doesn't exist!"); } }
/** * 监测复制进度(留意buffer的大小,对速度有很大影响) * * @param source * @param target */ public static void nioBufferCopy(File source, File target) { FileChannel in = null; FileChannel out = null; FileInputStream inStream = null; FileOutputStream outStream = null; try { inStream = new FileInputStream(source); outStream = new FileOutputStream(target); in = inStream.getChannel(); out = outStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(4096); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } } catch (IOException e) { e.printStackTrace(); } finally { close(inStream); close(in); close(outStream); close(out); } }
/** * 文件复制 * * @param s * @param t */ public static void fileCopy(File s, File t) { t.delete(); FileInputStream fi = null; FileOutputStream fo = null; FileChannel in = null; FileChannel out = null; try { fi = new FileInputStream(s); fo = new FileOutputStream(t); in = fi.getChannel(); // 得到对应的文件通道 out = fo.getChannel(); // 得到对应的文件通道 in.transferTo(0, in.size(), out); // 连接两个通道,并且从in通道读取,然后写入out通道 } catch (IOException e) { e.printStackTrace(); } finally { try { fi.close(); in.close(); fo.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
/** @param args */ public static void main(String[] args) throws Exception { // 读取的 地址 File fInput = new File(Config.inputAdd); // 读取流 FileInputStream fis = new FileInputStream(fInput); // 读取 管道 FileChannel inputChannel = fis.getChannel(); // lock方式 加 共享锁 System.out.println("主线程 在 控制文件fInput - 30秒 , 当前时间子线程 - >" + new Date()); FileLock lock = inputChannel.lock(0, fInput.length(), true); System.out.println("子线程 对 fInput 加上锁了。加上的时间为: " + new Date()); if (null != lock) { System.out.println("子线程开始执行 锁里面的操作了"); } else { System.out.println("按道理说 这句话 永远 不应该被打印 的....."); } lock.release(); // 释放资源 fis.close(); inputChannel.close(); }
public static ChannelByteIO stdIO() { FileInputStream input = new FileInputStream(FileDescriptor.in); FileOutputStream output = new FileOutputStream(FileDescriptor.out); FileChannel in = input.getChannel(); FileChannel out = output.getChannel(); return new ChannelByteIO(in, out); }
/** * Esse metodo serve para copiar um ou mais arquivos para outro diretorio. Exemplo: copy(new * String[]{"/home/andre/teste.txt","/home/andre/teste2.txt" },"/home/ariella/"); * * @param filenames * @param dest * @throws TSApplicationException */ public void copy(String[] filenames, String dest) throws TSApplicationException { String[] fileNamesNovo = new String[filenames.length]; FileOutputStream fout = null; FileInputStream fin = null; // Compress the files try { for (int i = 0; i < filenames.length; i++) { String novoArquivo = filenames[i].substring(filenames[i].lastIndexOf("/") + 1); fileNamesNovo[i] = dest + novoArquivo; // Cria a stream para ler o arquivo original fin = new FileInputStream(filenames[i]); fout = new FileOutputStream(fileNamesNovo[i]); // Cria a stream para gravar o arquivo de c�pia // Usa as streams para criar os canais correspondentes FileChannel in = fin.getChannel(); FileChannel outChannel = fout.getChannel(); // N�mero de bytes do arquivo original long numbytes = in.size(); // Transfere todo o volume para o arquivo de c�pia. in.transferTo(0, numbytes, outChannel); } } catch (FileNotFoundException e) { throw new TSApplicationException(TSConstant.MENSAGEM_FILE_NOT_FOUND); } catch (IOException e) { throw new TSApplicationException(TSConstant.MENSAGEM_ERRO_ENTRADA_SAIDA); } }
public static void main(String args[]) { try { aServer asr = new aServer(); // file channel. FileInputStream is = new FileInputStream(""); is.read(); FileChannel cha = is.getChannel(); ByteBuffer bf = ByteBuffer.allocate(1024); bf.flip(); cha.read(bf); // Path Paths Path pth = Paths.get("", ""); // Files some static operation. Files.newByteChannel(pth); Files.copy(pth, pth); // file attribute, other different class for dos and posix system. BasicFileAttributes bas = Files.readAttributes(pth, BasicFileAttributes.class); bas.size(); } catch (Exception e) { System.err.println(e); } System.out.println("hello "); }
public static String getMd5(File file) { if (file == null || !file.exists()) { return null; } String value = null; FileInputStream in = null; try { in = new FileInputStream(file); MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length()); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(byteBuffer); BigInteger bi = new BigInteger(1, md5.digest()); value = bi.toString(16); } catch (Exception e) { e.printStackTrace(); } finally { if (null != in) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return value; }
public static String getFileMD5String(File file) { FileInputStream in = null; FileChannel ch = null; MappedByteBuffer byteBuffer = null; try { in = new FileInputStream(file); ch = in.getChannel(); byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length()); messagedigest.update(byteBuffer); } catch (IOException e) { e.printStackTrace(); } finally { if (ch != null) { try { ch.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } IOUtils.closeQuietly(in); } return bufferToHex(messagedigest.digest()); }
// Read up to 'len' bytes of Value. Value should already be persisted to // disk. A racing delete can trigger a failure where we get a null return, // but no crash (although one could argue that a racing load&delete is a bug // no matter what). @Override public byte[] load(Value v) { long skip = 0; Key k = v._key; // Convert an arraylet chunk into a long-offset from the base file. if (k._kb[0] == Key.ARRAYLET_CHUNK) { skip = ValueArray.getChunkOffset(k); // The offset k = ValueArray.getArrayKey(k); // From the base file key } if (k._kb[0] == Key.DVEC) { skip = water.fvec.NFSFileVec.chunkOffset(k); // The offset } try { FileInputStream s = null; try { s = new FileInputStream(getFileForKey(k)); FileChannel fc = s.getChannel(); fc.position(skip); AutoBuffer ab = new AutoBuffer(fc, true, Value.NFS); byte[] b = ab.getA1(v._max); ab.close(); assert v.isPersisted(); return b; } finally { if (s != null) s.close(); } } catch (IOException e) { // Broken disk / short-file??? H2O.ignore(e); return null; } }
/** * 读取到字节数组2 * * @param filePath * @return * @throws IOException */ public static byte[] toByteArray2(String filePath) throws IOException { File f = new File(filePath); if (!f.exists()) { throw new FileNotFoundException(filePath); } FileChannel channel = null; FileInputStream fs = null; try { fs = new FileInputStream(f); channel = fs.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size()); while ((channel.read(byteBuffer)) > 0) { // do nothing // System.out.println("reading"); } return byteBuffer.array(); } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { channel.close(); } catch (IOException e) { e.printStackTrace(); } try { fs.close(); } catch (IOException e) { e.printStackTrace(); } } }
@Override protected void loadFromByteBuffer(String fileName) throws IOException, MaryConfigurationException { /* Open the file */ FileInputStream fis = new FileInputStream(fileName); FileChannel fc = fis.getChannel(); ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); fis.close(); /* Load the Mary header */ hdr = new MaryHeader(bb); if (hdr.getType() != MaryHeader.HALFPHONE_UNITFEATS) { throw new MaryConfigurationException( "File [" + fileName + "] is not a valid Mary Halfphone Features file."); } leftWeights = new FeatureDefinition(bb); rightWeights = new FeatureDefinition(bb); assert leftWeights.featureEquals(rightWeights) : "Halfphone unit feature file contains incompatible feature definitions for left and right units -- this should not happen!"; featureDefinition = leftWeights; // one of them, for super class int numberOfUnits = bb.getInt(); featureVectors = new FeatureVector[numberOfUnits]; for (int i = 0; i < numberOfUnits; i++) { featureVectors[i] = featureDefinition.readFeatureVector(i, bb); } }
/** * 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 + "'"); } }
@Override public void writeTo( FileRange fileRange, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { long fileSize = fileRange.getFile().length(); String contentRange = "bytes " + fileRange.getBegin() + "-" + fileRange.getEnd() + "/" + fileSize; long length = (fileRange.getEnd() - fileRange.getBegin()) + 1; httpHeaders.putSingle("Content-Range", contentRange); httpHeaders.putSingle("Content-Length", length); FileInputStream fis = new FileInputStream(fileRange.getFile()); try { if (fileRange.getBegin() > 0) { fis.getChannel().position(fileRange.getBegin()); } final byte[] buf = new byte[2048]; while (length > 0) { int len = 2048 > length ? (int) length : 2048; int read = fis.read(buf, 0, len); if (read == -1) { break; } entityStream.write(buf, 0, read); length -= len; } } finally { fis.close(); } }
public ObjectStream<ChunkSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); language = params.getLang(); FileInputStream sampleDataIn = CmdLineUtil.openInFile(params.getData()); ObjectStream<String> lineStream = new PlainTextByLineStream(sampleDataIn.getChannel(), params.getEncoding()); ADChunkBasedShallowParserSampleStream sampleStream = new ADChunkBasedShallowParserSampleStream( lineStream, params.getFunctTags(), params.getIsIncludePOSTags(), params.getUseCGTags(), params.getExpandME()); if (params.getStart() != null && params.getStart() > -1) { sampleStream.setStart(params.getStart()); } if (params.getEnd() != null && params.getEnd() > -1) { sampleStream.setEnd(params.getEnd()); } return sampleStream; }
public void run(String[] args) { String script = null; try { FileInputStream stream = new FileInputStream(new File(args[0])); try { FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); script = Charset.availableCharsets().get("UTF-8").decode(bb).toString(); } finally { stream.close(); } } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } Context cx = Context.enter(); try { ScriptableObject scope = cx.initStandardObjects(); scope.putConst("language", scope, "java"); scope.putConst("platform", scope, "android"); scope.put("util", scope, new Util(cx, scope)); cx.evaluateString(scope, script, args[0], 1, null); } catch (Error ex) { ex.printStackTrace(); System.exit(1); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } finally { Context.exit(); } System.exit(0); }
/** * Based on <a href="http://www.screaming-penguin.com/node/7749">Backing up your Android SQLite * database to the SD card</a> * * @param src * @param dst * @return true if success * @throws IOException */ boolean copyFile(File src, File dst) throws IOException { long sizeIn = -1; long sizeCopied = 0; boolean ok = false; if (src != null && src.exists()) { sizeIn = src.length(); if (!dst.createNewFile()) { MyLog.e(this, "New file was not created: '" + dst.getCanonicalPath() + "'"); } else if (src.getCanonicalPath().compareTo(dst.getCanonicalPath()) == 0) { MyLog.d(this, "Cannot copy to itself: '" + src.getCanonicalPath() + "'"); } else { FileInputStream fileInputStream = null; java.nio.channels.FileChannel inChannel = null; FileOutputStream fileOutputStream = null; java.nio.channels.FileChannel outChannel = null; try { fileInputStream = new FileInputStream(src); inChannel = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(dst); outChannel = fileOutputStream.getChannel(); sizeCopied = inChannel.transferTo(0, inChannel.size(), outChannel); ok = (sizeIn == sizeCopied); } finally { DbUtils.closeSilently(outChannel); DbUtils.closeSilently(fileOutputStream); DbUtils.closeSilently(inChannel); DbUtils.closeSilently(fileInputStream); } } } MyLog.d(this, "Copied " + sizeCopied + " bytes of " + sizeIn); return ok; }
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()); } }
public static void copyFile(File srcFile, File destFile) throws Exception { int bufferSize = 2048; FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); FileChannel inChannel = in.getChannel(); FileChannel outChannel = out.getChannel(); ByteBuffer buffer = null; int length = -1; try { while (true) { if (inChannel.position() == inChannel.size()) { // finish copying break; } else if (inChannel.size() - inChannel.position() < length) { // copy last chunk of data length = (int) (inChannel.size() - inChannel.position()); } else { length = bufferSize; } buffer = ByteBuffer.allocateDirect(length); inChannel.read(buffer); buffer.flip(); outChannel.write(buffer); outChannel.force(false); } } finally { _close(inChannel); _close(in); _close(outChannel); _close(out); } }