List of usage examples for java.io FileInputStream getChannel
public FileChannel getChannel()
From source file:jackpal.androidterm.Term.java
private void copyFileToClipboard(String filename) { if (filename == null) return;/*from w w w .j a v a2s .c o m*/ FileInputStream fis; try { fis = new FileInputStream(filename); FileChannel fc = fis.getChannel(); try { ByteBuffer bbuf; bbuf = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int) fc.size()); // Create a read-only CharBuffer on the file CharBuffer cbuf = Charset.forName("UTF-8").newDecoder().decode(bbuf); String str = cbuf.toString(); ClipboardManagerCompat clip = ClipboardManagerCompatFactory.getManager(getApplicationContext()); clip.setText(str); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.wandora.application.gui.topicpanels.ProcessingTopicPanel.java
private String buildSource(String sketch) { boolean useTemplate = false; // maybe make this an option in the future try {/*from w w w . ja va 2 s . co m*/ // classIdentifier = System.currentTimeMillis(); if (useTemplate) { // processingClassName="SketchTemplate"; String sketchTemplate = ""; FileInputStream stream = new FileInputStream(new File(sketchPath + "SketchTemplate.java")); try { FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); /* Instead of using default, pass in a decoder. */ sketchTemplate = Charset.defaultCharset().decode(bb).toString(); } finally { stream.close(); } String upperPart = sketchTemplate.substring(0, sketchTemplate.indexOf(tempReplaceStart) + 1); linesBeforeCode = upperPart.split(System.getProperty("line.separator")).length - 1; //System.out.println("Lines before code "+linesBeforeCode); charactersBefore = sketchTemplate.indexOf(tempReplaceStart); //temp = temp.substring(temp.indexOf("\n")); String fullSource = sketchTemplate.substring(0, sketchTemplate.indexOf(tempReplaceStart)) + sketch + sketchTemplate.substring(sketchTemplate.indexOf(tempReplaceEnd) + tempReplaceEnd.length(), sketchTemplate.length()); // fullSource = fullSource.replaceAll("(?:SketchTemplate)", processingClassName+classIdentifier); // fullSource = fullSource.replaceFirst("(?:PApplet)", "SketchTemplate"); return fullSource; } else { // (?m) turns on multi-line mode so ^ and $ match line start and end Pattern p = Pattern.compile("(?m)^\\s*package\\s+processing\\s*;\\s*$"); if (!p.matcher(sketch).find()) { throw new Exception( "The sketch file must be defined to be in the \"processing\" package. Add \"package processing;\" at the start of the sketch or modify the existing package declaration."); } return sketch; } } catch (Exception ex) { Logger.getLogger(ProcessingTopicPanel.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return null; }
From source file:com.marklogic.client.functionaltest.BasicJavaClientREST.java
/** * Copy Files from One location to Other * @param Source File//from w w w.j a v a 2s . c o m * @param target File * @param Boolean Value * @throws FileNotFoundException */ public void copyWithChannels(File aSourceFile, File aTargetFile, boolean aAppend) { //log("Copying files with channels."); //ensureTargetDirectoryExists(aTargetFile.getParentFile()); FileChannel inChannel = null; FileChannel outChannel = null; FileInputStream inStream = null; FileOutputStream outStream = null; try { try { inStream = new FileInputStream(aSourceFile); inChannel = inStream.getChannel(); outStream = new FileOutputStream(aTargetFile, aAppend); outChannel = outStream.getChannel(); long bytesTransferred = 0; //defensive loop - there's usually only a single iteration : while (bytesTransferred < inChannel.size()) { bytesTransferred += inChannel.transferTo(0, inChannel.size(), outChannel); } } finally { //being defensive about closing all channels and streams if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); if (inStream != null) inStream.close(); if (outStream != null) outStream.close(); } } catch (FileNotFoundException ex) { System.out.println("File not found: " + ex); } catch (IOException ex) { System.out.println(ex); } }
From source file:com.taobao.common.tfs.DefaultTfsManager.java
/************************************ * sort of specified implementation *//from w w w.ja v a 2s .c om ************************************/ private String saveFileEx(FileInputStream input, String tfsFileName, String tfsSuffix, int type, String key, boolean simpleName) throws TfsException, IOException { if (input == null) { log.error("args 'input' is null"); return null; } TfsFile file; if (type == TFS_LARGE_FILE_TYPE) { file = filePool.getLargeFile(); ((TfsLargeFile) file).open(tfsFileName, tfsSuffix, TfsConstant.WRITE_MODE, key); } else if (type == TFS_SMALL_FILE_TYPE) { file = filePool.getFile(); log.info(tfsFileName + "," + tfsSuffix + "," + TfsConstant.WRITE_MODE); file.open(tfsFileName, tfsSuffix, TfsConstant.WRITE_MODE); } else { throw new TfsException("local file is empty or too large. not support now."); } long length = input.getChannel().size(); log.info("length:" + length); // read from local at most int perLength = (int) Math.min(TfsFile.MAX_LARGE_IO_LENGTH, length); log.info("perLength:" + perLength); byte[] data = new byte[perLength]; int readLength = 0; while (length > 0) { readLength = input.read(data, 0, perLength); if (readLength > 0) { file.write(data, 0, readLength); length -= readLength; } else { break; } } file.close(); String retName = file.getFileName(simpleName); log.info(retName); log.info((simpleName ? retName + (null == tfsSuffix ? "" : tfsSuffix) : retName)); return (simpleName ? retName + (null == tfsSuffix ? "" : tfsSuffix) : retName); }
From source file:gephi.spade.panel.fcsFile.java
/** * extractEvents ---//from w w w . jav a2 s . c om * <p> * Extracts the events from the FCS file using NIO. * </p> * * @throws <code>java.io.FileNotFoundException</code> if the file is not * found. * @throws <code>java.io.IOException</code> if an IO exception occurred. */ private void extractEvents() throws FileNotFoundException, IOException { if ((dataStart >= dataEnd) || (totalEvents <= 0)) { // If the byte offset of the start of the DATA segment is greater // than or equal to the end of the DATA segment or the number of // events is equal to 0, then create an empty array of events. eventList = new double[0][parameters]; return; } // Open a file input stream to the file FileInputStream fis = new FileInputStream(file); // Get the channel for the file FileChannel fc = fis.getChannel(); // Map the DATA segment to memory MappedByteBuffer data; try { data = fc.map(FileChannel.MapMode.READ_ONLY, dataStart, dataEnd - dataStart + 1); } catch (Throwable t) { // Try again with a workaround to see if we can compensate for off-by-one errors that // some FCS files have been known to incorporate in the ENDDATA property. data = fc.map(FileChannel.MapMode.READ_ONLY, dataStart, dataEnd - dataStart); } /** * We don't need to worry about endian-ness here since ASCII is one * byte, and float and double are IEEE standards. */ if (dataType != null) { if (dataType.equalsIgnoreCase("I")) { // If the data type is "I", then it is binary integer. readBinIntData(data); } else if (dataType.equalsIgnoreCase("F")) { // If the data type is "F", then it is floating point. readFloatData(data); } else if (dataType.equalsIgnoreCase("D")) { // If the data type is "D", then it is double precision floating // point readDoubleData(data); } else if (dataType.equalsIgnoreCase("A")) { // If the data type is "A", then it is ASCII. readASCIIData(data); } } // Close the file channel fc.close(); // Close the file input stream fis.close(); }
From source file:com.example.util.FileUtils.java
/** * Internal copy file method./*from w w w. j av a2s. co m*/ * * @param srcFile the validated source file, must not be {@code null} * @param destFile the validated destination file, must not be {@code null} * @param preserveFileDate whether to preserve the file date * @throws IOException if an error occurs */ private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) 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 > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos; pos += output.transferFrom(input, pos, count); } } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(input); IOUtils.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
From source file:com.vegnab.vegnab.MainVNActivity.java
public void copyFile(File src, File dst) throws IOException { FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dst); FileChannel fromChannel = null, toChannel = null; try {// w w w . j a va2s . co m fromChannel = in.getChannel(); toChannel = out.getChannel(); fromChannel.transferTo(0, fromChannel.size(), toChannel); } finally { if (fromChannel != null) fromChannel.close(); if (toChannel != null) toChannel.close(); } in.close(); out.close(); // must do following or file is not visible externally MediaScannerConnection.scanFile(getApplicationContext(), new String[] { dst.getAbsolutePath() }, null, null); }
From source file:com.matteoveroni.model.copy.FileUtils.java
/** * Internal copy file method.//from ww w . j ava2 s .c o m * * @param srcFile the validated source file, must not be {@code null} * @param destFile the validated destination file, must not be {@code null} * @param preserveFileDate whether to preserve the file date * @throws IOException if an error occurs */ private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) 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 { bytesTransferedTotal = 0; 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 > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos; //pos += output.transferFrom(input, pos, count); //Split into into deceleration and assignment to count bytes transfered long bytesTransfered = output.transferFrom(input, pos, count); //complete original method pos += bytesTransfered; //update total bytes copied, so it can be used to calculate progress bytesTransferedTotal += bytesTransfered; System.out.println((int) Math.floor((100.0 / size) * bytesTransferedTotal) + "%"); } } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(input); IOUtils.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
From source file:com.benefit.buy.library.http.query.AbstractAQuery.java
/** * Create a temporary file on EXTERNAL storage (sdcard) that holds the cached content of the url. Returns null if * url is not cached, or the system cannot create such file (sdcard is absent, such as in emulator). The returned * file is accessable to all apps, therefore it is ideal for sharing content (such as photo) via the intent * mechanism. <br>//w ww. j av a 2s . co m * <br> * Example Usage: * * <pre> * Intent intent = new Intent(Intent.ACTION_SEND); * intent.setType("image/jpeg"); * intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); * startActivityForResult(Intent.createChooser(intent, "Share via:"), 0); * </pre> * * <br> * The temp file will be deleted when AQUtility.cleanCacheAsync is invoked, or the file can be explicitly deleted * after use. * @param url The url of the desired cached content. * @param filename The desired file name, which might be used by other apps to describe the content, such as an * email attachment. * @return temp file */ public File makeSharedFile(String url, String filename) { File file = null; try { File cached = getCachedFile(url); if (cached != null) { File temp = AQUtility.getTempDir(); if (temp != null) { file = new File(temp, filename); file.createNewFile(); FileInputStream fis = new FileInputStream(cached); FileOutputStream fos = new FileOutputStream(file); FileChannel ic = fis.getChannel(); FileChannel oc = fos.getChannel(); try { ic.transferTo(0, ic.size(), oc); } finally { AQUtility.close(fis); AQUtility.close(fos); AQUtility.close(ic); AQUtility.close(oc); } } } } catch (Exception e) { AQUtility.debug(e); } return file; }