List of usage examples for java.nio.channels Channels newChannel
public static WritableByteChannel newChannel(OutputStream out)
From source file:siddur.solidtrust.newprice2.Newprice2Controller.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("file") MultipartFile file, Model model, HttpSession session) throws IOException { //upload/*w w w. j ava2 s.c om*/ log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize()); File temp = File.createTempFile("data", ".csv"); log4j.info("Will save to " + temp.getAbsolutePath()); InputStream in = null; FileOutputStream fout = null; try { fout = new FileOutputStream(temp); FileChannel fcout = fout.getChannel(); in = file.getInputStream(); ReadableByteChannel cin = Channels.newChannel(in); ByteBuffer buf = ByteBuffer.allocate(1024 * 8); while (true) { buf.clear(); int r = cin.read(buf); if (r == -1) { break; } buf.flip(); fcout.write(buf); } } finally { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } FileStatus fs = new FileStatus(); fs.setFile(temp); log4j.info("Uploading complete"); //fields BufferedReader br = null; int[] orders; String[] fields; try { in = new FileInputStream(temp); br = new BufferedReader(new InputStreamReader(in)); //first line for fields String firstLine = br.readLine(); fields = StringUtils.split(firstLine, ";"); ; orders = new int[fields.length]; for (int i = 0; i < orders.length; i++) { orders[i] = ArrayUtils.indexOf(FIELDS, fields[i].trim()); } //count while (br.readLine() != null) { fs.next(); } } finally { if (br != null) { br.close(); } } fs.flip(); log4j.info("Total rows: " + fs.getTotalRow()); //persist carService.saveCars(fs, orders, carService); return "redirect:/v2/upload.html"; }
From source file:com.xxxifan.devbox.library.rxfile.RxFile.java
private static File fileFromUri(Context context, Uri data) throws Exception { DocumentFile file = DocumentFile.fromSingleUri(context, data); String fileType = file.getType(); String fileName = file.getName(); File fileCreated;//from w w w. j a v a 2 s . co m ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(data, Constants.READ_MODE); InputStream inputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor()); Log.e(TAG, "External cache dir:" + context.getExternalCacheDir()); String filePath = context.getExternalCacheDir() + Constants.FOLDER_SEPARATOR + fileName; String fileExtension = fileName.substring((fileName.lastIndexOf('.')) + 1); String mimeType = getMimeType(fileName); Log.e(TAG, "From Drive guessed type: " + getMimeType(fileName)); Log.e(TAG, "Extension: " + fileExtension); if (fileType.equals(Constants.APPLICATION_PDF) && mimeType == null) { filePath += "." + Constants.PDF_EXTENSION; } if (!createFile(filePath)) { return new File(filePath); } ReadableByteChannel from = Channels.newChannel(inputStream); WritableByteChannel to = Channels.newChannel(new FileOutputStream(filePath)); fastChannelCopy(from, to); from.close(); to.close(); fileCreated = new File(filePath); Log.e(TAG, "Path for made file: " + fileCreated.getAbsolutePath()); return fileCreated; }
From source file:com.rogue.logore.update.UpdateHandler.java
/** * Downloads the latest jarfile for the {@link Plugin} * * @since 1.0.0//from ww w.j a v a 2 s.com * @version 1.0.0 * * @TODO Add zip file support * @return The download result */ public Result download() { Result back = Result.UPDATED; File updateFolder = this.plugin.getServer().getUpdateFolderFile(); String url = (String) this.latest.get(this.DL_URL); ReadableByteChannel rbc = null; FileOutputStream fos = null; try { URL call = new URL(url); rbc = Channels.newChannel(call.openStream()); fos = new FileOutputStream(this.file); fos.getChannel().transferFrom(rbc, 0, 1 << 24); } catch (MalformedURLException ex) { this.plugin.getLogger().log(Level.SEVERE, "Error finding plugin update to download!", ex); back = Result.ERROR_FILENOTFOUND; } catch (IOException ex) { this.plugin.getLogger().log(Level.SEVERE, "Error transferring plugin data!", ex); back = Result.ERROR_DOWNLOAD_FAILED; } finally { try { if (fos != null) { fos.close(); } if (rbc != null) { rbc.close(); } } catch (IOException ex) { this.plugin.getLogger().log(Level.SEVERE, "Error closing streams/channels for download!", ex); } } return back; }
From source file:it.doqui.index.ecmengine.business.personalization.multirepository.FileContentWriterDynamic.java
@Override protected WritableByteChannel getDirectWritableChannel() throws ContentIOException { try {//from w w w .ja v a 2s. c o m // we may not write to an existing file - EVER!! if (file.exists() && file.length() > 0) { throw new IOException("File exists - overwriting not allowed"); } // create the channel WritableByteChannel channel = null; if (allowRandomAccess) { RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); // will create it channel = randomAccessFile.getChannel(); } else { OutputStream os = new FileOutputStream(file); channel = Channels.newChannel(os); } // done if (logger.isDebugEnabled()) { logger.debug("Opened write channel to file: \n" + " file: " + file + "\n" + " random-access: " + allowRandomAccess); } return channel; } catch (Throwable e) { throw new ContentIOException("Failed to open file channel: " + this, e); } }
From source file:siddur.solidtrust.fault.FaultController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("file") MultipartFile file, @RequestParam("version") int v, Model model, HttpSession session) throws Exception { IFaultPersister persister = getPersister(v); //upload//from ww w . j a va2 s . co m log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize()); File temp = File.createTempFile("data", ".csv"); log4j.info("Will save to " + temp.getAbsolutePath()); InputStream in = null; FileOutputStream fout = null; try { fout = new FileOutputStream(temp); FileChannel fcout = fout.getChannel(); in = file.getInputStream(); ReadableByteChannel cin = Channels.newChannel(in); ByteBuffer buf = ByteBuffer.allocate(1024 * 8); while (true) { buf.clear(); int r = cin.read(buf); if (r == -1) { break; } buf.flip(); fcout.write(buf); } } finally { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } log4j.info("Uploading complete"); //fields BufferedReader br = null; int[] orders; try { in = new FileInputStream(temp); br = new BufferedReader(new InputStreamReader(in)); //first line for fields String firstLine = br.readLine(); orders = persister.validateTitle(firstLine); //persist persister.parseAndSave(br, orders, persister); } finally { if (br != null) { br.close(); } } return "redirect:upload.html"; }
From source file:org.biopax.psidev.ontology_manager.impl.OboLoader.java
/** * Load an OBO file from an URL./*w w w . j ava 2s . c om*/ * * @param url the URL to load (must not be null) * @return an ontology * @see #parseOboFile(File, String) */ public OntologyAccess parseOboFile(URL url, String ontologyID) throws OntologyLoaderException { // load config file (ie. a map) // check if that URL has already been loaded // if so, get the associated temp file and check if available // if available, then load it and skip URL load // if any of the above failed, load it from the network. if (url == null) { throw new IllegalArgumentException("Please give a non null URL."); } File ontologyFile = null; try { if (ontologyFile == null || !ontologyFile.exists() || !ontologyFile.canRead()) { // if it is not defined, not there or not readable... // Read URL content log.info("Loading URL: " + url); URLConnection con = url.openConnection(); long size = con.getContentLength(); // -1 if not stat available log.info("size = " + size); InputStream is = url.openStream(); // make the temporary file name specific to the URL String name = null; String filename = url.getFile(); int idx = filename.lastIndexOf('/'); if (idx != -1) { name = filename.substring(idx + 1, filename.length()); name = name.replaceAll("[.,;:&^%$@*?=]", "_"); } else { name = "unknown"; } ontologyFile = Files.createTempFile(name + "_", ".obo").toFile(); ontologyFile.deleteOnExit(); log.debug("The OBO file will be temporary stored as: " + ontologyFile.getAbsolutePath()); FileOutputStream out = new FileOutputStream(ontologyFile); if (size == -1) size = 1024 * 1024 * 1024; //Integer.MAX_VALUE; ReadableByteChannel source = Channels.newChannel(is); size = out.getChannel().transferFrom(source, 0, size); log.info(size + " bytes downloaded"); is.close(); out.flush(); out.close(); } if (ontologyFile == null) { log.error("The ontology file is still null..."); } // Parse file return parseOboFile(ontologyFile, ontologyID); } catch (IOException e) { throw new OntologyLoaderException("Error while loading URL (" + url + ")", e); } }
From source file:com.doplgangr.secrecy.FileSystem.File.java
public java.io.File readFile(CryptStateListener listener) { decrypting = true;//from w w w . j av a 2 s. c o m InputStream is = null; OutputStream out = null; java.io.File outputFile = null; try { outputFile = java.io.File.createTempFile("tmp" + name, "." + FileType, storage.getTempFolder()); outputFile.mkdirs(); outputFile.createNewFile(); AES_Encryptor enc = new AES_Encryptor(key); is = new CipherInputStream(new FileInputStream(file), enc.decryptstream()); listener.setMax((int) file.length()); ReadableByteChannel inChannel = Channels.newChannel(is); FileChannel outChannel = new FileOutputStream(outputFile).getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(Config.bufferSize); while (inChannel.read(byteBuffer) >= 0 || byteBuffer.position() > 0) { byteBuffer.flip(); outChannel.write(byteBuffer); byteBuffer.compact(); listener.updateProgress((int) outChannel.size()); } inChannel.close(); outChannel.close(); Util.log(outputFile.getName(), outputFile.length()); return outputFile; } catch (FileNotFoundException e) { listener.onFailed(2); Util.log("Encrypted File is missing", e.getMessage()); } catch (IOException e) { Util.log("IO Exception while decrypting", e.getMessage()); if (e.getMessage().contains("pad block corrupted")) listener.onFailed(1); else e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { listener.Finished(); decrypting = false; try { if (is != null) { is.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } // An error occured. Too Bad if (outputFile != null) storage.purgeFile(outputFile); return null; }
From source file:org.eclipse.packagedrone.utils.rpm.build.PayloadRecorder.java
public Result addFile(final String targetPath, final ByteBuffer data, final Consumer<CpioArchiveEntry> customizer) throws IOException { final long size = data.remaining(); final CpioArchiveEntry entry = new CpioArchiveEntry(targetPath); entry.setSize(size);/* www . j a v a 2 s.co m*/ if (customizer != null) { customizer.accept(entry); } this.archiveStream.putArchiveEntry(entry); // record digest MessageDigest digest; try { digest = createDigest(); digest.update(data.slice()); } catch (final NoSuchAlgorithmException e) { throw new IOException(e); } // write data final WritableByteChannel channel = Channels.newChannel(this.archiveStream); while (data.hasRemaining()) { channel.write(data); } // close archive entry this.archiveStream.closeArchiveEntry(); return new Result(size, digest.digest()); }
From source file:com.discovery.darchrow.io.IOWriteUtil.java
/** * NIO API ?? ()./*from w w w . j a v a 2s . c om*/ * * @param bufferLength * the buffer length * @param inputStream * the input stream * @param outputStream * the output stream * @since 1.0.8 * @since jdk1.4 */ private static void writeUseNIO(int bufferLength, InputStream inputStream, OutputStream outputStream) { int i = 0; int sumSize = 0; int j = 0; ///2 //As creme de la creme with regard to performance, you could use NIO Channels and ByteBuffer. ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream); WritableByteChannel writableByteChannel = Channels.newChannel(outputStream); ByteBuffer byteBuffer = ByteBuffer.allocate(bufferLength); try { while (readableByteChannel.read(byteBuffer) != -1) { byteBuffer.flip(); j = writableByteChannel.write(byteBuffer); sumSize += j; byteBuffer.clear(); i++; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Write data over,sumSize:[{}],bufferLength:[{}],loopCount:[{}]", FileUtil.formatSize(sumSize), bufferLength, i); } } catch (IOException e) { throw new UncheckedIOException(e); } finally { IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(writableByteChannel); IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(readableByteChannel); } }
From source file:at.ac.tuwien.infosys.util.ImageUtil.java
private void saveFile(URL url, Path file) throws IOException { ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileChannel channel = FileChannel.open(file, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)); channel.transferFrom(rbc, 0, Long.MAX_VALUE); channel.close();//w w w . j a va2 s . c o m }