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); } }
public static long copyFile(java.nio.file.Path srcfile, java.nio.file.Path dstfile) throws java.io.IOException { java.nio.channels.FileChannel inchan = java.nio.channels.FileChannel.open(srcfile, OPENOPTS_READ); java.nio.channels.FileChannel outchan = null; long nbytes = 0; long filesize; try { filesize = inchan.size(); outchan = java.nio.channels.FileChannel.open(dstfile, OPENOPTS_CREATE_WRITE_TRUNC); nbytes = outchan.transferFrom(inchan, 0, inchan.size()); } finally { try { inchan.close(); } catch (Exception ex) { } if (outchan != null) try { outchan.close(); } catch (Exception ex) { } } if (nbytes != filesize) throw new java.io.IOException( "file-copy=" + nbytes + " vs " + filesize + " for " + srcfile + " => " + dstfile); return nbytes; }
/** * Create a PerfDataBuffer instance for accessing the specified instrumentation buffer. * * @param vmid the <em>file:</em> URI to the instrumentation buffer file * @throws MonitorException */ public PerfDataBuffer(VmIdentifier vmid) throws MonitorException { File f = new File(vmid.getURI()); String mode = vmid.getMode(); try { FileChannel fc = new RandomAccessFile(f, mode).getChannel(); ByteBuffer bb = null; if (mode.compareTo("r") == 0) { bb = fc.map(FileChannel.MapMode.READ_ONLY, 0L, (int) fc.size()); } else if (mode.compareTo("rw") == 0) { bb = fc.map(FileChannel.MapMode.READ_WRITE, 0L, (int) fc.size()); } else { throw new IllegalArgumentException("Invalid mode: " + mode); } fc.close(); // doesn't need to remain open createPerfDataBuffer(bb, 0); } catch (FileNotFoundException e) { throw new MonitorException("Could not find " + vmid.toString()); } catch (IOException e) { throw new MonitorException("Could not read " + vmid.toString()); } }
public static BlockLink[] loadBlockMatches(String fileName) { File f = new File(fileName); if (!f.exists()) { return null; } try { FileChannel roChannel = new RandomAccessFile(f, "r").getChannel(); int count = (int) ((roChannel.size() - 1) / 6); ByteBuffer buffer = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, roChannel.size()); roChannel.close(); buffer.order(ByteOrder.LITTLE_ENDIAN); if (buffer.get() != version) { return null; } BlockLink[] links = new BlockLink[count]; for (int i = 0; i < links.length; i++) { links[i] = new BlockLink(buffer.getShort(), buffer.get(), buffer.get(), buffer.getShort()); } return links; } catch (Exception e) { e.printStackTrace(); return null; } }
public boolean storeFilesUpgradeable(File neoStoreFile) { File storeDirectory = neoStoreFile.getParentFile(); for (String fileName : fileNamesToExpectedVersions.keySet()) { String expectedVersion = fileNamesToExpectedVersions.get(fileName); FileChannel fileChannel = null; byte[] expectedVersionBytes = UTF8.encode(expectedVersion); try { File storeFile = new File(storeDirectory, fileName); if (!fs.fileExists(storeFile)) { return false; } fileChannel = fs.open(storeFile, "r"); if (fileChannel.size() < expectedVersionBytes.length) { return false; } fileChannel.position(fileChannel.size() - expectedVersionBytes.length); byte[] foundVersionBytes = new byte[expectedVersionBytes.length]; fileChannel.read(ByteBuffer.wrap(foundVersionBytes)); if (!expectedVersion.equals(UTF8.decode(foundVersionBytes))) { return false; } } catch (IOException e) { throw new RuntimeException(e); } finally { if (fileChannel != null) { try { fileChannel.close(); } catch (IOException e) { // Ignore exception on close } } } } return true; }
public void put(String key, String value) throws IOException { int hash = hash(key); int i = indexFor(hash, capacity); int position = i * block_size; WordBlock b = readWordBlock(position); for (; b.nextPosition > 0; b = readWordBlock(b.nextPosition)) { Object k; if (hash(b.word) == hash && ((k = b.word) == key || key.equals(k))) { b.translate = value; writeWordBlock(b); return; } } if (b.nextPosition == 0) { b = new WordBlock(b.position); } else { int nextPosition = 0; if (fileChannel.size() > capacity * block_size) { nextPosition = (int) fileChannel.size(); } else { nextPosition = capacity * block_size; } System.out.println(key + " " + b.word); b.nextPosition = nextPosition; writeWordBlock(b); b = new WordBlock(nextPosition); } b.word = key; b.translate = value; b.nextPosition = -1; writeWordBlock(b); }
private boolean loadFromFile() { File GeoCrc = new File(fileName); if (!GeoCrc.exists()) { return false; } try { FileChannel roChannel = new RandomAccessFile(GeoCrc, "r").getChannel(); if (roChannel.size() != GeoEngine.BLOCKS_IN_MAP * 4) { roChannel.close(); return false; } ByteBuffer buffer = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, roChannel.size()); roChannel.close(); buffer.order(ByteOrder.LITTLE_ENDIAN); int[] _checkSums = new int[GeoEngine.BLOCKS_IN_MAP]; for (int i = 0; i < GeoEngine.BLOCKS_IN_MAP; i++) { _checkSums[i] = buffer.getInt(); } checkSums[geoX][geoY] = _checkSums; return true; } catch (Exception e) { e.printStackTrace(); return false; } }
/** * Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能 * * @param filename * @return * @throws IOException */ public static byte[] toByteArray3(String filePath) throws IOException { FileChannel fc = null; RandomAccessFile rf = null; try { rf = new RandomAccessFile(filePath, "r"); fc = rf.getChannel(); MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0, fc.size()).load(); // System.out.println(byteBuffer.isLoaded()); byte[] result = new byte[(int) fc.size()]; if (byteBuffer.remaining() > 0) { // System.out.println("remain"); byteBuffer.get(result, 0, byteBuffer.remaining()); } return result; } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { rf.close(); fc.close(); } catch (IOException e) { e.printStackTrace(); } } }
public void write(Tag tag, RandomAccessFile raf, RandomAccessFile tempRaf) throws CannotWriteException, IOException { FileChannel fc = raf.getChannel(); int oldTagSize = 0; if (tagExists(fc)) { // read the length if (!canOverwrite(raf)) throw new CannotWriteException("Overwritting of this kind of ID3v2 tag not supported yet"); fc.position(6); ByteBuffer buf = ByteBuffer.allocate(4); fc.read(buf); oldTagSize = (buf.get(0) & 0xFF) << 21; oldTagSize += (buf.get(1) & 0xFF) << 14; oldTagSize += (buf.get(2) & 0xFF) << 7; oldTagSize += buf.get(3) & 0xFF; oldTagSize += 10; // System.err.println("Old tag size: "+oldTagSize); int newTagSize = tc.getTagLength(tag); if (oldTagSize >= newTagSize) { // replace // System.err.println("Old ID32v Tag found, replacing the old // tag"); fc.position(0); fc.write(tc.convert(tag, oldTagSize - newTagSize)); // ID3v2 Tag Written return; } } // create new tag with padding // System.err.println("Creating a new ID3v2 Tag"); fc.position(oldTagSize); if (fc.size() > 15 * 1024 * 1024) { FileChannel tempFC = tempRaf.getChannel(); tempFC.position(0); tempFC.write(tc.convert(tag, Id3v2TagCreator.DEFAULT_PADDING)); tempFC.transferFrom(fc, tempFC.position(), fc.size() - oldTagSize); fc.close(); } else { ByteBuffer[] content = new ByteBuffer[2]; content[1] = ByteBuffer.allocate((int) fc.size()); fc.read(content[1]); content[1].rewind(); content[0] = tc.convert(tag, Id3v2TagCreator.DEFAULT_PADDING); fc.position(0); fc.write(content); } }
private static void testExceptions(FileChannel fc) throws IOException { checkException(fc, null, 0L, fc.size(), NullPointerException.class); checkException(fc, MapMode.READ_ONLY, -1L, fc.size(), IllegalArgumentException.class); checkException( fc, null, -1L, fc.size(), IllegalArgumentException.class, NullPointerException.class); checkException(fc, MapMode.READ_ONLY, 0L, -1L, IllegalArgumentException.class); checkException(fc, null, 0L, -1L, IllegalArgumentException.class, NullPointerException.class); checkException( fc, MapMode.READ_ONLY, 0L, Integer.MAX_VALUE + 1L, IllegalArgumentException.class); checkException( fc, null, 0L, Integer.MAX_VALUE + 1L, IllegalArgumentException.class, NullPointerException.class); checkException(fc, MapMode.READ_ONLY, Long.MAX_VALUE, 1L, IllegalArgumentException.class); checkException( fc, null, Long.MAX_VALUE, 1L, IllegalArgumentException.class, NullPointerException.class); }
// from https://gist.github.com/889747 // TODO use Jakarta Commons IO..! This implementation needs to be improved. private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileInputStream fIn = null; FileOutputStream fOut = null; FileChannel source = null; FileChannel destination = null; try { fIn = new FileInputStream(sourceFile); source = fIn.getChannel(); fOut = new FileOutputStream(destFile); destination = fOut.getChannel(); long transfered = 0; long bytes = source.size(); while (transfered < bytes) { transfered += destination.transferFrom(source, 0, source.size()); destination.position(transfered); } } finally { if (source != null) { source.close(); } else if (fIn != null) { fIn.close(); } if (destination != null) { destination.close(); } else if (fOut != null) { fOut.close(); } } }
@Test public void testSize() throws IOException { RegularFile file = regularFile(10); FileChannel channel = channel(file, READ); assertEquals(10, channel.size()); file.write(10, new byte[90], 0, 90); assertEquals(100, channel.size()); }
public void run() { FileChannel channel = null; ByteBuffer buffer = null; buffer = ByteBuffer.allocate(262144); if (this.logListener != null) this.logListener.inicioLog(null); try { while (isContinuar()) { channel = new FileInputStream(this.arquivo).getChannel(); if (channel.size() > this.bytesLidos) { int lidos = 0; while ((lidos = channel.read(buffer, this.bytesLidos)) != -1) { buffer.flip(); byte[] b = new byte[lidos]; buffer.get(b); if (this.logListener != null) this.logListener.log(new String(b)); buffer.clear(); this.bytesLidos += lidos; } } else if (channel.size() < this.bytesLidos) { this.bytesLidos = (this.arquivo.length() - 16384L); if (this.bytesLidos < 0L) this.bytesLidos = 0L; if (this.logListener != null) this.logListener.log( System.getProperty("line.separator") + "********Parte do arquivo foi apagada. Reinicializando leitura********" + System.getProperty("line.separator")); } try { Thread.sleep(500L); } catch (InterruptedException e) { e.printStackTrace(); setContinuar(false); } channel.close(); } } catch (IOException e) { e.printStackTrace(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintStream s = new PrintStream(bos); e.printStackTrace(s); s.flush(); JOptionPane.showMessageDialog(null, new ErroPainel(new String(bos.toByteArray())), "Erro", 0); } finally { if ((channel != null) && (!channel.isOpen())) try { channel.close(); } catch (IOException localIOException1) { } } }
public static void copyFile(File srcFile, File dstFile) { if (!dstFile.exists()) { try { dstFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(srcFile).getChannel(); destination = new FileOutputStream(dstFile).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (IOException e) { e.printStackTrace(); } finally { if (source != null) { try { source.close(); } catch (IOException e) { e.printStackTrace(); } } if (destination != null) { try { destination.close(); } catch (IOException e) { e.printStackTrace(); } } } }
public long getContentLength() { try { return Math.min(mChunkSize, mChannel.size() - mChannel.position()); } catch (IOException e) { return mChunkSize; } }
/** Reply a specific WAL. */ private void replayLog(Path logPath) throws KevaDBException { // Now look at the disk. if (logPath != null) { // Get a list of the sstables already in place. Map<String, Integer> manifest = db.getDiskService().getDataManifests(db, 0, SSTableService.MAX_LEVELS); FileLock fileLock = null; try { // Must open in "rw" mode so that we can use filelock. FileChannel fc = FileChannel.open(logPath, StandardOpenOption.READ, StandardOpenOption.WRITE); MappedByteBuffer in = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int) fc.size()); fileLock = fc.tryLock(); if (fileLock != null) { for (; ; ) { if (!unroll(in, manifest)) { break; } } } if (fileLock != null) { fileLock.release(); } fc.close(); } catch (IOException e) { e.printStackTrace(); } } }
private ByteList bufferedRead(int number) throws IOException, BadDescriptorException { checkReadable(); ensureRead(); int resultSize = 0; // 128K seems to be the minimum at which the stat+seek is faster than reallocation final int BULK_THRESHOLD = 128 * 1024; if (number >= BULK_THRESHOLD && descriptor.isSeekable() && descriptor.getChannel() instanceof FileChannel) { // // If it is a file channel, then we can pre-allocate the output buffer // to the total size of buffered + remaining bytes in file // FileChannel fileChannel = (FileChannel) descriptor.getChannel(); resultSize = (int) Math.min( fileChannel.size() - fileChannel.position() + bufferedInputBytesRemaining(), number); } else { // // Cannot discern the total read length - allocate at least enough for the buffered data // resultSize = Math.min(bufferedInputBytesRemaining(), number); } ByteList result = new ByteList(resultSize); bufferedRead(result, number); return result; }
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!"); } }
/** * Parses the FileChannel, in the range [start, end) and prints the elements found * * <p>Elements are printed, indented by "level" number of spaces. If an element is a container, * then its contents will be, recursively, printed, with a greater indentation. * * @param fc * @param level * @param start * @param end * @throws IOException */ private void print(FileChannel fc, int level, long start, long end) throws IOException { fc.position(start); if (end <= 0) { end = start + fc.size(); System.out.println("Setting END to " + end); } while (end - fc.position() > 8) { long begin = fc.position(); ByteBuffer bb = ByteBuffer.allocate(8); fc.read(bb); bb.rewind(); long size = IsoTypeReader.readUInt32(bb); String type = IsoTypeReader.read4cc(bb); long fin = begin + size; // indent by the required number of spaces for (int i = 0; i < level; i++) { System.out.print(" "); } System.out.println(type + "@" + (begin) + " size: " + size); if (containers.contains(type)) { print(fc, level + 1, begin + 8, fin); if (fc.position() != fin) { System.out.println("End of container contents at " + fc.position()); System.out.println(" FIN = " + fin); } } else { } fc.position(fin); } }
/** * 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; }
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); }
private static long getRecord(String storeDir, long recordPosition) { RandomAccessFile file = null; try { file = new RandomAccessFile(new File(storeDir), "rw"); FileChannel channel = file.getChannel(); /* * We have to check size, because the store version * field was introduced with 1.5, so if there is a non-clean * shutdown we may have a buffer underflow. */ if (recordPosition > 3 && channel.size() < RECORD_SIZE * 5) { return -1; } channel.position(RECORD_SIZE * recordPosition + 1 /*inUse*/); ByteBuffer buffer = ByteBuffer.allocate(8); channel.read(buffer); buffer.flip(); long previous = buffer.getLong(); return previous; } catch (IOException e) { throw new RuntimeException(e); } finally { try { if (file != null) file.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
public void writeRequest(final OutputStream out) throws IOException { int readCount = 0; Iterator<OnDatatransferProgressListener> it = null; try { mChannel.position(mOffset); long size = mFile.length(); if (size == 0) size = -1; long maxCount = Math.min(mOffset + mChunkSize, mChannel.size()); while (mChannel.position() < maxCount) { readCount = mChannel.read(mBuffer); out.write(mBuffer.array(), 0, readCount); mBuffer.clear(); if (mTransferred < maxCount) { // condition to avoid accumulate progress for repeated chunks mTransferred += readCount; } synchronized (mDataTransferListeners) { it = mDataTransferListeners.iterator(); while (it.hasNext()) { it.next().onTransferProgress(readCount, mTransferred, size, mFile.getName()); } } } } catch (IOException io) { Log.e(TAG, io.getMessage()); throw new RuntimeException( "Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); } }
/*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; }
private void insertRecord(int recordPosition, long value) throws IOException { try { FileChannel channel = getFileChannel(); long previousPosition = channel.position(); channel.position(RECORD_SIZE * recordPosition); int trail = (int) (channel.size() - channel.position()); ByteBuffer trailBuffer = null; if (trail > 0) { trailBuffer = ByteBuffer.allocate(trail); channel.read(trailBuffer); trailBuffer.flip(); } ByteBuffer buffer = ByteBuffer.allocate(RECORD_SIZE); buffer.put(Record.IN_USE.byteValue()); buffer.putLong(value); buffer.flip(); channel.position(RECORD_SIZE * recordPosition); channel.write(buffer); if (trail > 0) { channel.write(trailBuffer); } channel.position(previousPosition); } catch (IOException e) { throw new RuntimeException(e); } }
public void copy() { try { File sd = AndroidSensors.DataPath; File data = Environment.getDataDirectory(); if (sd.exists() == false) sd.mkdirs(); String currentDBPath = "//data//" + "winlab.sensoradventure" + "//databases//" + "InstantReading.db"; String backupDBPath = "InstantReading.db"; File currentDB = new File(data, currentDBPath); File backupDB = new File(sd, backupDBPath); FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); Message msg = handler.obtainMessage(); msg.arg1 = 1; handler.sendMessage(msg); } catch (Exception e) { Message msg = handler.obtainMessage(); msg.arg1 = 2; handler.sendMessage(msg); } }
/** * 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 + "'"); } }
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); } }
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(); }
public boolean backupConfig(@NonNull String sourceString, @NonNull String destString) { try { File sourceFile = new File(sourceString); File destFile = new File(destString); if (!sourceFile.exists()) return false; if (!destFile.exists()) destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } if (source != null) source.close(); if (destination != null) destination.close(); } catch (IOException ex) { Warning.load("Cannot backup config: " + sourceString, false); return false; } return true; }