List of usage examples for java.io FileInputStream getChannel
public FileChannel getChannel()
From source file:fr.acxio.tools.agia.tasks.FileCopyTaskletTest.java
@Test public void testCannotEmptyOrigin() throws Exception { FileCopyTasklet aTasklet = new FileCopyTasklet(); aTasklet.setOrigin(new FileSystemResource("src/test/resources/testFiles/input.csv")); aTasklet.setDestination(new FileSystemResource("target/input-copy8.csv")); aTasklet.execute(null, null);/*from w w w . j a v a 2 s . co m*/ File aOrigin = aTasklet.getDestination().getFile(); assertTrue(aOrigin.exists()); FileInputStream aInputStream = new FileInputStream(aOrigin); FileLock aLock = aInputStream.getChannel().lock(0L, Long.MAX_VALUE, true); // shared lock aTasklet.setEmptyOrigin(true); aTasklet.setOrigin(new FileSystemResource("target/input-copy8.csv")); aTasklet.setDestination(new FileSystemResource("target/input-copy9.csv")); try { aTasklet.execute(null, null); fail("Must throw a FileCopyException"); } catch (FileCopyException e) { // Fallthrough } finally { aLock.release(); aInputStream.close(); } }
From source file:com.frostwire.gui.library.LibraryCoverArt.java
private Image retrieveImageFromM4A(String filename) { try {/* ww w . jav a 2s . c o m*/ FileInputStream fis = new FileInputStream(filename); try { FileChannel inFC = fis.getChannel(); IsoFile iso = new IsoFile(inFC); Path p = new Path(iso); AppleDataBox data = (AppleDataBox) p.getPath("/moov/udta/meta/ilst/covr/data"); if (data != null) { if ((data.getFlags() & 0x1) == 0x1) { // jpg byte[] imageBytes = data.getData(); try { return ImageIO.read(new ByteArrayInputStream(imageBytes, 0, imageBytes.length)); } catch (IIOException e) { return JPEGImageIO.read(new ByteArrayInputStream(imageBytes, 0, imageBytes.length)); } } else if ((data.getFlags() & 0x2) == 0x2) { // png byte[] imageBytes = data.getData(); try { return ImageIO.read(new ByteArrayInputStream(imageBytes, 0, imageBytes.length)); } catch (IIOException e) { return null; } } } } finally { fis.close(); } } catch (Throwable e) { //LOG.error("Unable to read cover art from m4a"); } return null; }
From source file:com.geekandroid.sdk.sample.crop.ResultActivity.java
private void copyFileToDownloads(Uri croppedFileUri) throws Exception { String downloadsDirectoryPath = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(); String filename = String.format("%d_%s", Calendar.getInstance().getTimeInMillis(), croppedFileUri.getLastPathSegment()); File saveFile = new File(downloadsDirectoryPath, filename); FileInputStream inStream = new FileInputStream(new File(croppedFileUri.getPath())); FileOutputStream outStream = new FileOutputStream(saveFile); FileChannel inChannel = inStream.getChannel(); FileChannel outChannel = outStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); inStream.close();// ww w.ja va2s .com outStream.close(); showNotification(saveFile); }
From source file:eu.linda.analytics.formats.RDFInputFormat.java
@Override public AbstractList importData4weka(String query_id, boolean isForRDFOutput, Analytics analytics) { String queryURI = connectionController.getQueryURI(query_id); helpfulFunctions.nicePrintMessage("import data from uri " + queryURI); Instances data = null;//ww w . j a va 2 s .co m try { float timeToGetQuery = 0; long startTimeToGetQuery = System.currentTimeMillis(); URL url = new URL(queryURI); if (!helpfulFunctions.isURLResponsive(url)) { return null; } File tmpfile4lindaquery = File.createTempFile("tmpfile4lindaquery" + query_id, ".tmp"); FileUtils.copyURLToFile(url, tmpfile4lindaquery); System.out.println("Downloaded File Query: " + tmpfile4lindaquery); CSVLoader loader = new CSVLoader(); loader.setSource(tmpfile4lindaquery); if (isForRDFOutput) { loader.setStringAttributes("1,2"); } loader.setFieldSeparator(","); data = loader.getDataSet(); data.setClassIndex(data.numAttributes() - 1); FileInputStream fis = null; try { fis = new FileInputStream(tmpfile4lindaquery); System.out.println("fis.getChannel().size() " + fis.getChannel().size()); analytics.setData_size(analytics.getData_size() + fis.getChannel().size()); } finally { fis.close(); } // Get elapsed time in milliseconds long elapsedTimeToGetQueryMillis = System.currentTimeMillis() - startTimeToGetQuery; // Get elapsed time in seconds timeToGetQuery = elapsedTimeToGetQueryMillis / 1000F; analytics.setTimeToGet_data(analytics.getTimeToGet_data() + timeToGetQuery); System.out.println("timeToGetQuery" + timeToGetQuery); connectionController.updateLindaAnalyticsInputDataPerformanceTime(analytics); } catch (Exception ex) { Logger.getLogger(ArffInputFormat.class.getName()).log(Level.SEVERE, null, ex); } return data; }
From source file:tachyon.shell.command.CopyFromLocalCommand.java
private void copyPath(File src, TachyonURI dstPath) throws IOException { try {// w w w. java2 s .com if (!src.isDirectory()) { // If the dstPath is a directory, then it should be updated to be the path of the file where // src will be copied to if (mFileSystem.exists(dstPath) && mFileSystem.getStatus(dstPath).isFolder()) { dstPath = dstPath.join(src.getName()); } Closer closer = Closer.create(); FileOutStream os = null; try { os = closer.register(mFileSystem.createFile(dstPath)); FileInputStream in = closer.register(new FileInputStream(src)); FileChannel channel = closer.register(in.getChannel()); ByteBuffer buf = ByteBuffer.allocate(8 * Constants.MB); while (channel.read(buf) != -1) { buf.flip(); os.write(buf.array(), 0, buf.limit()); } } catch (IOException e) { // Close the out stream and delete the file, so we don't have an incomplete file lying // around if (os != null) { os.cancel(); if (mFileSystem.exists(dstPath)) { mFileSystem.delete(dstPath); } } throw e; } finally { closer.close(); } } else { mFileSystem.createDirectory(dstPath); List<String> errorMessages = Lists.newArrayList(); String[] fileList = src.list(); for (String file : fileList) { TachyonURI newPath = new TachyonURI(dstPath, new TachyonURI(file)); File srcFile = new File(src, file); try { copyPath(srcFile, newPath); } catch (IOException e) { errorMessages.add(e.getMessage()); } } if (errorMessages.size() != 0) { if (errorMessages.size() == fileList.length) { // If no files were created, then delete the directory if (mFileSystem.exists(dstPath)) { mFileSystem.delete(dstPath); } } throw new IOException(Joiner.on('\n').join(errorMessages)); } } } catch (TachyonException e) { throw new IOException(e.getMessage()); } }
From source file:net.praqma.jenkins.memorymap.parser.AbstractMemoryMapParser.java
protected CharSequence createCharSequenceFromFile(String charset, File f) throws IOException { String chosenCharset = charset; CharBuffer cbuf = null;// w w w .j av a 2 s. c om FileInputStream fis = null; try { fis = new FileInputStream(f.getAbsolutePath()); FileChannel fc = fis.getChannel(); ByteBuffer bbuf = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int) fc.size()); if (!Charset.isSupported(chosenCharset)) { logger.warning(String.format("The charset %s is not supported", charset)); cbuf = Charset.defaultCharset().newDecoder().decode(bbuf); } else { cbuf = Charset.forName(charset).newDecoder().decode(bbuf); } } catch (IOException ex) { throw ex; } finally { if (fis != null) { fis.close(); } } return cbuf; }
From source file:eu.linda.analytics.formats.RDFInputFormat.java
@Override public Rengine importData4R(String query_id, boolean isForRDFOutput, Analytics analytics) { System.out.println(System.getProperty("java.library.path")); System.out.println("R_HOME" + System.getenv().get("R_HOME")); Rengine re = Rengine.getMainEngine(); if (re == null) { // re = new Rengine(new String[]{"--vanilla"}, false, null); String newargs[] = { "--no-save" }; re = new Rengine(newargs, false, null); }/*from ww w. j ava 2 s .c o m*/ if (!re.waitForR()) { System.out.println("Cannot load R"); System.out.println("is alive Rengine??" + re.isAlive()); } String queryURI = connectionController.getQueryURI(query_id); helpfulFunctions.nicePrintMessage("import data from uri " + queryURI); try { float timeToGetQuery = 0; long startTimeToGetQuery = System.currentTimeMillis(); URL url = new URL(queryURI); if (!helpfulFunctions.isURLResponsive(url)) { re.eval(" is_query_responsive <-FALSE "); System.out.println("is_query_responsive <-FALSE "); } else { re.eval("is_query_responsive <-TRUE "); System.out.println("is_query_responsive <-TRUE "); File tmpfile4lindaquery = File.createTempFile("tmpfile4lindaquery" + query_id, ".tmp"); FileUtils.copyURLToFile(url, tmpfile4lindaquery); re.eval(" loaded_data <- read.csv(file='" + tmpfile4lindaquery + "', header=TRUE, sep=',', na.strings='---');"); System.out.println(" loaded_data <- read.csv(file='" + tmpfile4lindaquery + "', header=TRUE, sep=',', na.strings='---');"); FileInputStream fis = null; try { fis = new FileInputStream(tmpfile4lindaquery); System.out.println("fis.getChannel().size() " + fis.getChannel().size()); analytics.setData_size(analytics.getData_size() + fis.getChannel().size()); } finally { fis.close(); } } // Get elapsed time in milliseconds long elapsedTimeToGetQueryMillis = System.currentTimeMillis() - startTimeToGetQuery; // Get elapsed time in seconds timeToGetQuery = elapsedTimeToGetQueryMillis / 1000F; System.out.println("timeToGetQuery" + timeToGetQuery); analytics.setTimeToGet_data(analytics.getTimeToGet_data() + timeToGetQuery); connectionController.updateLindaAnalyticsInputDataPerformanceTime(analytics); } catch (Exception ex) { Logger.getLogger(ArffInputFormat.class.getName()).log(Level.SEVERE, null, ex); } return re; }
From source file:com.yifanlu.PSXperiaTool.ZpakCreate.java
public void create(boolean noCompress) throws IOException { Logger.info("Generating zpak file from directory %s with compression = %b", mDirectory.getPath(), !noCompress);//from ww w . j a v a2 s. c o m IOFileFilter filter = new IOFileFilter() { public boolean accept(File file) { if (file.getName().startsWith(".")) { Logger.debug("Skipping file %s", file.getPath()); return false; } return true; } public boolean accept(File file, String s) { if (s.startsWith(".")) { Logger.debug("Skipping file %s", file.getPath()); return false; } return true; } }; Iterator<File> it = FileUtils.iterateFiles(mDirectory, filter, TrueFileFilter.INSTANCE); ZipOutputStream out = new ZipOutputStream(mOut); out.setMethod(noCompress ? ZipEntry.STORED : ZipEntry.DEFLATED); while (it.hasNext()) { File current = it.next(); FileInputStream in = new FileInputStream(current); ZipEntry zEntry = new ZipEntry( current.getPath().replace(mDirectory.getPath(), "").substring(1).replace("\\", "/")); if (noCompress) { zEntry.setSize(in.getChannel().size()); zEntry.setCompressedSize(in.getChannel().size()); zEntry.setCrc(getCRC32(current)); } out.putNextEntry(zEntry); Logger.verbose("Adding file %s", current.getPath()); int n; while ((n = in.read(mBuffer)) != -1) { out.write(mBuffer, 0, n); } in.close(); out.closeEntry(); } out.close(); Logger.debug("Done with ZPAK creation."); }
From source file:org.dataconservancy.dcs.access.server.TransformerServiceImpl.java
@Override public String fgdcToHtml(String inputUrl, String format) { if (format.contains("fgdc")) { TransformerFactory factory = TransformerFactory.newInstance(); Source xslt = new StreamSource(new File(homeDir + "queryFgdcResult.xsl")); Transformer transformer;//from w w w .ja v a2 s . co m try { transformer = factory.newTransformer(xslt); String inputPath = homeDir + UUID.randomUUID().toString() + "fgdcinput.xml"; saveUrl(inputPath, inputUrl); Source text = new StreamSource(new File(inputPath)); String outputPath = homeDir + UUID.randomUUID().toString() + "fgdcoutput.html"; File outputFile = new File(outputPath); transformer.transform(text, new StreamResult(outputFile)); FileInputStream stream = new FileInputStream(new File(outputPath)); try { FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); /* Instead of using default, pass in a decoder. */ return Charset.defaultCharset().decode(bb).toString(); } finally { stream.close(); } } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { String inputPath = //getServletContext().getContextPath()+"/xml/"+ homeDir + UUID.randomUUID().toString() + "fgdcinput.xml"; saveUrl(inputPath, inputUrl); Source text = new StreamSource(new File( //"/home/kavchand/Desktop/fgdc.xml" inputPath)); FileInputStream stream = new FileInputStream(new File(inputPath)); FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); /* Instead of using default, pass in a decoder. */ return Charset.defaultCharset().decode(bb).toString(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; }
From source file:org.granite.grails.web.GrailsWebSWFServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID, grailsAttributes); // Get the name of the Groovy script (intern the name so that we can lock on it) String pageName = "/swf" + request.getServletPath(); Resource requestedFile = getResourceForUri(pageName); File swfFile = requestedFile.getFile(); if (swfFile == null || !swfFile.exists()) { response.sendError(404, "\"" + pageName + "\" not found."); return;//from w w w . ja v a2 s . c o m } response.setContentType("application/x-shockwave-flash"); response.setContentLength((int) swfFile.length()); response.setBufferSize((int) swfFile.length()); response.setDateHeader("Expires", 0); FileInputStream is = null; FileChannel inChan = null; try { is = new FileInputStream(swfFile); OutputStream os = response.getOutputStream(); inChan = is.getChannel(); long fSize = inChan.size(); MappedByteBuffer mBuf = inChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); byte[] buf = new byte[(int) fSize]; mBuf.get(buf); os.write(buf); } finally { if (is != null) { IOUtils.closeQuietly(is); } if (inChan != null) { try { inChan.close(); } catch (IOException ignored) { } } } }