List of usage examples for java.io FileInputStream getChannel
public FileChannel getChannel()
From source file:com.kappaware.logtrawler.MFile.java
/** * //from w w w . j av a2 s . c om * @return false is the file can't be opened, whatever is the reason * @throws IOException */ void open() throws IOException { try { Utils.assertNull(this.channel, "Channel must be null on open on %s", this.path); Utils.assertNull(this.reader, "Reader must be null on open on %s", this.path); FileInputStream fis = new FileInputStream(this.path.toFile()); this.channel = fis.getChannel(); this.channel.position(this.position); this.reader = new BufferedReader(new InputStreamReader(fis)); // Need this, otherwise will be the oldest, so removed before used. this.lastAccessTime = System.currentTimeMillis(); return; } catch (IOException e) { //log.error(String.format("Unable to open file '%s'", this.path), e); if (this.channel != null) { try { this.channel.close(); } catch (IOException e1) { } } throw e; } }
From source file:net.ytbolg.mcxa.ImportOldMc.java
void fileChannelCopy(File s, File t) { FileInputStream fi = null; FileOutputStream fo = null;/*w w w. j a va 2s. c o m*/ 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(); } } }
From source file:com.amazonaws.internal.ResettableInputStream.java
/** * @param file/*w w w.j a v a 2 s . c o m*/ * can be null if not known */ private ResettableInputStream(FileInputStream fis, File file) throws IOException { super(fis); this.file = file; this.fis = fis; this.fileChannel = fis.getChannel(); this.markPos = fileChannel.position(); }
From source file:com.frostwire.util.MP4Muxer.java
public void demuxAudio(String video, String output, final MP4Metadata mt) throws IOException { FileInputStream videoIn = new FileInputStream(video); try {//from www . j a va 2 s.c o m FileChannel videoChannel = videoIn.getChannel(); Movie videoMovie = buildMovie(videoChannel); Track audioTrack = null; for (Track trk : videoMovie.getTracks()) { if (trk.getHandler().equals("soun")) { audioTrack = trk; break; } } if (audioTrack == null) { IOUtils.closeQuietly(videoIn); return; } Movie outMovie = new Movie(); outMovie.addTrack(audioTrack); Container out = new DefaultMp4Builder() { @Override protected FileTypeBox createFileTypeBox(Movie movie) { List<String> minorBrands = new LinkedList<String>(); minorBrands.add("M4A "); minorBrands.add("mp42"); minorBrands.add("isom"); minorBrands.add("\0\0\0\0"); return new FileTypeBox("M4A ", 0, minorBrands); } @Override protected MovieBox createMovieBox(Movie movie, Map<Track, int[]> chunks) { MovieBox moov = super.createMovieBox(movie, chunks); moov.getMovieHeaderBox().setVersion(0); return moov; } @Override protected TrackBox createTrackBox(Track track, Movie movie, Map<Track, int[]> chunks) { TrackBox trak = super.createTrackBox(track, movie, chunks); trak.getTrackHeaderBox().setVersion(0); trak.getTrackHeaderBox().setVolume(1.0f); return trak; } @Override protected Box createUdta(Movie movie) { return mt != null ? addUserDataBox(mt) : null; } }.build(outMovie); FileOutputStream fos = new FileOutputStream(output); try { out.writeContainer(fos.getChannel()); } finally { IOUtils.closeQuietly(fos); } } finally { IOUtils.closeQuietly(videoIn); } }
From source file:com.panet.imeta.trans.steps.fixedinput.FixedInput.java
public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta = (FixedInputMeta) smi;/* www . ja v a2s . c o m*/ data = (FixedInputData) sdi; if (super.init(smi, sdi)) { try { data.preferredBufferSize = Integer.parseInt(environmentSubstitute(meta.getBufferSize())); data.lineWidth = Integer.parseInt(environmentSubstitute(meta.getLineWidth())); data.filename = environmentSubstitute(meta.getFilename()); if (Const.isEmpty(data.filename)) { logError(Messages.getString("FixedInput.MissingFilename.Message")); return false; } FileObject fileObject = KettleVFS.getFileObject(data.filename); try { FileInputStream fileInputStream = KettleVFS.getFileInputStream(fileObject); data.fc = fileInputStream.getChannel(); data.bb = ByteBuffer.allocateDirect(data.preferredBufferSize); } catch (IOException e) { logError(e.toString()); return false; } // Add filename to result filenames ? if (meta.isAddResultFile()) { ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, fileObject, getTransMeta().getName(), toString()); resultFile.setComment("File was read by a Fixed input step"); addResultFile(resultFile); } logBasic("Opened file with name [" + data.filename + "]"); data.stopReading = false; if (meta.isRunningInParallel()) { data.stepNumber = getUniqueStepNrAcrossSlaves(); data.totalNumberOfSteps = getUniqueStepCountAcrossSlaves(); data.fileSize = fileObject.getContent().getSize(); } // OK, now we need to skip a number of bytes in case we're doing a parallel read. // if (meta.isRunningInParallel()) { int totalLineWidth = data.lineWidth + meta.getLineSeparatorLength(); // including line separator bytes long nrRows = data.fileSize / totalLineWidth; // 100.000 / 100 = 1000 rows long rowsToSkip = Math.round(data.stepNumber * nrRows / (double) data.totalNumberOfSteps); // 0, 333, 667 long nextRowsToSkip = Math .round((data.stepNumber + 1) * nrRows / (double) data.totalNumberOfSteps); // 333, 667, 1000 data.rowsToRead = nextRowsToSkip - rowsToSkip; long bytesToSkip = rowsToSkip * totalLineWidth; logBasic("Step #" + data.stepNumber + " is skipping " + bytesToSkip + " to position in file, then it's reading " + data.rowsToRead + " rows."); data.fc.position(bytesToSkip); } return true; } catch (IOException e) { logError("Error opening file '" + meta.getFilename() + "' : " + e.toString()); logError(Const.getStackTracker(e)); } } return false; }
From source file:edu.rit.flick.util.FlickTest.java
private final void testForLosslessness() throws IOException, InterruptedException { Flick.main(VERBOSE_FLAG, originalFile.getPath()); Unflick.main(VERBOSE_FLAG, flickedFile.getPath(), unflickedFile.getPath()); if (!originalFile.exists()) { /*/*from w ww. j a va 2s . co m*/ * By falling in here, we assume the test failed because the file * given as input was not found. Equally so, the flicked file will * not be found by the unflicker since no flicking would have been * able to occur. */ final String expectedUsageStatement = String.format("%s%n%s%n", new NoSuchFileException(originalFile.getPath(), null, AbstractFlickFile.FILE_NOT_FOUND_EXCEPTION_MESSAGE).getMessage().trim(), new NoSuchFileException(flickedFile.getPath(), null, AbstractFlickFile.FILE_NOT_FOUND_EXCEPTION_MESSAGE).getMessage().trim()); final Object[] errorStack = errContent.toString().split("\n"); final int eSl = errorStack.length; final String actualUsageStatement = String.format("%s\n%s\n", Arrays.copyOfRange(errorStack, eSl - 2, eSl)); assertEquals(expectedUsageStatement, actualUsageStatement); return; } final FileInputStream origFIS = new FileInputStream(originalFile); ByteBufferInputStream orig = ByteBufferInputStream.map(origFIS.getChannel()); final FileInputStream comAndDecomFIS = new FileInputStream(unflickedFile); ByteBufferInputStream comAndDecom = ByteBufferInputStream.map(comAndDecomFIS.getChannel()); if (!FileUtils.contentEquals(originalFile, unflickedFile)) { long position = 0; while (orig.available() > 0) { position++; final int o = orig.read(); final int c = comAndDecom.read(); assertEquals(format(FILES_DO_NOT_MATCH_ERROR_FORMAT, originalFile, unflickedFile, position), (char) o + "", (char) c + ""); } assertEquals(orig.available(), comAndDecom.available()); origFIS.close(); orig.close(); comAndDecomFIS.close(); comAndDecom.close(); orig = null; comAndDecom = null; } }
From source file:com.filemanager.free.filesystem.FileUtil.java
/** * Copy a file. The target file may even be on external SD card for Kitkat. * * @param source The source file//from ww w.j a va2 s . co m * @param target The target file * @return true if the copying was successful. */ @SuppressWarnings("null") public static boolean copyFile(final File source, final File target, Context context) { FileInputStream inStream = null; OutputStream outStream = null; FileChannel inChannel = null; FileChannel outChannel = null; try { inStream = new FileInputStream(source); // First try the normal way if (isWritable(target)) { // standard way outStream = new FileOutputStream(target); inChannel = inStream.getChannel(); outChannel = ((FileOutputStream) outStream).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // Storage Access Framework DocumentFile targetDocument = getDocumentFile(target, false, context); outStream = context.getContentResolver().openOutputStream(targetDocument.getUri()); } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { // Workaround for Kitkat ext SD card Uri uri = MediaStoreHack.getUriFromFile(target.getAbsolutePath(), context); outStream = context.getContentResolver().openOutputStream(uri); } else { return false; } if (outStream != null) { // Both for SAF and for Kitkat, write to output stream. byte[] buffer = new byte[16384]; // MAGIC_NUMBER int bytesRead; while ((bytesRead = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } } } } catch (Exception e) { Log.e("AmazeFileUtils", "Error when copying file from " + source.getAbsolutePath() + " to " + target.getAbsolutePath(), e); return false; } finally { try { inStream.close(); } catch (Exception e) { // ignore exception } try { outStream.close(); } catch (Exception e) { // ignore exception } try { inChannel.close(); } catch (Exception e) { // ignore exception } try { outChannel.close(); } catch (Exception e) { // ignore exception } } return true; }
From source file:org.chromium.APKPackager.java
private void copyFile(File src, File dest) throws FileNotFoundException, IOException { FileInputStream istream = new FileInputStream(src); FileOutputStream ostream = new FileOutputStream(dest); FileChannel input = istream.getChannel(); FileChannel output = ostream.getChannel(); try {/*from ww w. ja v a2s. com*/ input.transferTo(0, input.size(), output); } finally { istream.close(); ostream.close(); input.close(); output.close(); } }
From source file:wicket.protocol.http.FilePageStore.java
/** * @see wicket.protocol.http.SecondLevelCacheSessionStore.IPageStore#getPage(java.lang.String, * int, int)//w ww . j a v a2 s . c o m */ public Page getPage(String sessionId, int id, int versionNumber) { File sessionDir = new File(workDir, sessionId); if (sessionDir.exists()) { File pageFile = getPageFile(id, versionNumber, sessionDir); if (pageFile.exists()) { FileInputStream fis = null; try { byte[] pageData = null; fis = new FileInputStream(pageFile); int length = (int) pageFile.length(); ByteBuffer bb = ByteBuffer.allocate(length); fis.getChannel().read(bb); if (bb.hasArray()) { pageData = bb.array(); } else { pageData = new byte[length]; bb.get(pageData); } Page page = (Page) Objects.byteArrayToObject(pageData); return page.getVersion(versionNumber); } catch (Exception e) { log.debug("Error loading page " + id + " with version " + versionNumber + " for the sessionid " + sessionId + " from disc", e); } finally { try { if (fis != null) { fis.close(); } } catch (IOException ex) { // ignore } } } } return null; }
From source file:org.carbondata.query.aggregator.impl.CustomAggregatorHelper.java
/** * Below method will be used to read the level files * * @param memberFile/* www . j a v a 2 s. c o m*/ * @param fileName * @throws IOException */ private void readLevelFileAndUpdateCache(File memberFile, String fileName) throws IOException { FileInputStream fos = null; FileChannel fileChannel = null; try { // create an object of FileOutputStream fos = new FileInputStream(memberFile); fileChannel = fos.getChannel(); Map<Integer, String> memberMap = surrogateKeyMap.get(fileName); if (null == memberMap) { memberMap = new HashMap<Integer, String>(CarbonCommonConstants.DEFAULT_COLLECTION_SIZE); surrogateKeyMap.put(fileName, memberMap); } long size = fileChannel.size(); int maxKey = 0; ByteBuffer rowlengthToRead = null; int len = 0; ByteBuffer row = null; int toread = 0; byte[] bb = null; String value = null; int surrogateValue = 0; boolean enableEncoding = Boolean.valueOf( CarbonProperties.getInstance().getProperty(CarbonCommonConstants.ENABLE_BASE64_ENCODING, CarbonCommonConstants.ENABLE_BASE64_ENCODING_DEFAULT)); while (fileChannel.position() < size) { rowlengthToRead = ByteBuffer.allocate(4); fileChannel.read(rowlengthToRead); rowlengthToRead.rewind(); len = rowlengthToRead.getInt(); if (len == 0) { continue; } row = ByteBuffer.allocate(len); fileChannel.read(row); row.rewind(); toread = row.getInt(); bb = new byte[toread]; row.get(bb); if (enableEncoding) { value = new String(Base64.decodeBase64(bb), Charset.defaultCharset()); } else { value = new String(bb, Charset.defaultCharset()); } surrogateValue = row.getInt(); memberMap.put(surrogateValue, value); // check if max key is less than Surrogate key then update the max key if (maxKey < surrogateValue) { maxKey = surrogateValue; } } } finally { CarbonUtil.closeStreams(fileChannel, fos); } }