List of usage examples for java.io FileOutputStream getChannel
public FileChannel getChannel()
From source file:com.mgmtp.perfload.perfalyzer.normalization.Normalizer.java
public void normalize(final File file) throws IOException { checkState(!file.isAbsolute(), "'file' must be relative"); String filePath = file.getPath(); String[] pathElements = split(getPath(filePath), SystemUtils.FILE_SEPARATOR); // strip out dir StrBuilder sb = new StrBuilder(); for (int i = 0; i < pathElements.length; ++i) { if (i == 1) { continue; // strip out dir, e. g. perfmon-logs, measuring-logs }//from ww w.j av a 2 s.c o m sb.appendSeparator(SystemUtils.FILE_SEPARATOR); sb.append(pathElements[i]); } String dirPath = sb.toString(); Map<String, FileChannel> channels = newHashMap(); List<OutputStream> outputStreams = newArrayList(); FileInputStream fis = null; try { fis = new FileInputStream(new File(sourceDir, filePath)); //relative to source dir for (Scanner scanner = new Scanner(fis.getChannel(), Charsets.UTF_8.name()); scanner.hasNext();) { String line = scanner.nextLine(); if (trimToNull(line) == null || line.startsWith("#")) { continue; } List<ChannelData> channelDataList = normalizingStrategy.normalizeLine(line); for (ChannelData channelData : channelDataList) { FileChannel channel = channels.get(channelData.getChannelKey()); if (channel == null) { String baseName = channelData.getChannelBaseName(); String key = channelData.getChannelKey(); String fileName = new File(dirPath, String.format("[%s][%s].csv", baseName, key)).getPath(); File destFile = new File(destDir, fileName); destFile.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(destFile); outputStreams.add(fos); channel = fos.getChannel(); channels.put(channelData.getChannelKey(), channel); } writeLineToChannel(channel, channelData.getValue(), Charsets.UTF_8); } } } finally { outputStreams.forEach(IOUtils::closeQuietly); closeQuietly(fis); } }
From source file:org.itstechupnorth.walrus.base.ArticleBuffer.java
public ArticleBuffer saveTo(File file) throws IOException { final FileOutputStream out = new FileOutputStream(file); saveTo(out.getChannel()).close(); out.close();/*www .j av a 2 s. c o m*/ return this; }
From source file:uk.ac.tgac.rampart.util.DependencyDownloader.java
public void downloadFromUrl(URL url, File localFile) throws IOException { System.out.print("Downloading: " + url.toString() + " ... "); ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileOutputStream fos = new FileOutputStream(localFile); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); if (!localFile.exists()) { System.err.println("Could not download: " + url.toString() + "; URL may have changed."); }//from w ww. ja va 2s . c om System.out.println("done."); }
From source file:com.googlecode.download.maven.plugin.internal.DownloadCache.java
private void saveIndex() throws Exception { if (!this.indexFile.exists()) { this.indexFile.createNewFile(); }/*from w w w . ja v a2 s .c o m*/ FileOutputStream out = new FileOutputStream(this.indexFile); try (ObjectOutputStream res = new ObjectOutputStream(out)) { try (FileLock lock = out.getChannel().lock()) { res.writeObject(index); } } }
From source file:com.respam.comniq.models.OMDBParser.java
public void requestOMDB(String movie, String year) { String imageURL;/* w ww . ja va 2 s.c om*/ // Location for downloading and storing thumbnails String path = System.getProperty("user.home") + File.separator + "comniq" + File.separator + "output" + File.separator + "thumbnails"; File userOutDir = new File(path); // Create Thumbnails directory if not present if (userOutDir.mkdirs()) { System.out.println(userOutDir + " was created"); } // Connect to OMDB API and fetch details try { // Proxy details HttpHost proxy = new HttpHost("web-proxy.in.hpecorp.net", 8080, "http"); // HttpClient client = HttpClientBuilder.create().build(); // Start of proxy client DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); CloseableHttpClient client = HttpClients.custom().setRoutePlanner(routePlanner).build(); // End of proxy client String uri = "http://www.omdbapi.com/?t=" + URLEncoder.encode(movie) + "&y=" + year; uri = uri.replace(" ", "%20"); HttpGet request = new HttpGet(uri); HttpResponse response = client.execute(request); String json = EntityUtils.toString(response.getEntity()); JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser.parse(json); // Excluding Non Movies if (null != jsonObject.get("Title")) { movieInfo.add(jsonObject); // Download the thumbnails if Poster URL present if (null != jsonObject.get("Poster")) { imageURL = ((String) jsonObject.get("Poster")); System.out.println(imageURL); URL thumbnail = new URL(imageURL); ReadableByteChannel rbc = Channels.newChannel(thumbnail.openStream()); FileOutputStream fos = new FileOutputStream( path + File.separator + jsonObject.get("Title") + ".jpg"); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } } } catch (ParseException | IOException | UnsupportedOperationException e) { e.printStackTrace(); } }
From source file:org.canova.image.lfw.LFWLoader.java
public void getIfNotExists() throws Exception { if (!lfwDir.exists()) { lfwDir.mkdir();//from w w w. j a va 2s . c om log.info("Grabbing LFW..."); URL website = new URL(LFW_URL); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); if (!lfwTarFile.exists()) lfwTarFile.createNewFile(); FileOutputStream fos = new FileOutputStream(lfwTarFile); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.flush(); IOUtils.closeQuietly(fos); rbc.close(); log.info("Downloaded lfw"); untarFile(baseDir, lfwTarFile); } File firstImage = null; try { firstImage = lfwDir.listFiles()[0].listFiles()[0]; } catch (Exception e) { FileUtils.deleteDirectory(lfwDir); log.warn("Error opening first image; probably corrupt download...trying again", e); getIfNotExists(); } //number of input neurons numPixelColumns = ArrayUtil.flatten(loader.fromFile(firstImage)).length; //each subdir is a person numNames = lfwDir.getAbsoluteFile().listFiles().length; @SuppressWarnings("unchecked") Collection<File> allImages = FileUtils.listFiles(lfwDir, org.apache.commons.io.filefilter.FileFileFilter.FILE, org.apache.commons.io.filefilter.DirectoryFileFilter.DIRECTORY); for (File f : allImages) { images.add(f.getAbsolutePath()); } for (File dir : lfwDir.getAbsoluteFile().listFiles()) outcomes.add(dir.getAbsolutePath()); }
From source file:org.deegree.maven.PortnumberMojo.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { PrintStream out = null;/*ww w . j a va 2 s . c o m*/ BufferedReader reader = null; FileLock lock = null; FileInputStream fis = null; try { File portfile = new File(System.getProperty("java.io.tmpdir") + "/portnumbers"); int port = 1025; if (portfile.exists()) { fis = new FileInputStream(portfile); reader = new BufferedReader(new InputStreamReader(fis, "UTF-8")); boolean read = false; while (!read) { try { port = Integer.parseInt(reader.readLine()) + 1; read = true; } catch (NumberFormatException e) { // someone is currently writing try { Thread.sleep(100); } catch (InterruptedException e1) { return; } finally { closeQuietly(out); closeQuietly(reader); closeQuietly(fis); } } } reader.close(); } if (port > 18000) { port = 1025; } getLog().info("Using portnumber " + port + " for this run."); project.getProperties().put("portnumber", "" + port); FileOutputStream fos = new FileOutputStream(portfile); out = new PrintStream(fos, true, "UTF-8"); while ((lock = fos.getChannel().tryLock()) == null) { try { Thread.sleep(100); } catch (InterruptedException e) { return; } } out.println("" + port); lock.release(); out.close(); } catch (Throwable e) { getLog().error(e); } finally { closeQuietly(out); closeQuietly(reader); closeQuietly(fis); } }
From source file:org.apache.hadoop.hdfs.server.datanode.TestDirectoryScannerInlineFiles.java
private void truncateFile(File f) throws IOException { assertTrue(f.exists() && f.length() != 0); FileOutputStream s = new FileOutputStream(f); FileChannel channel = s.getChannel(); channel.truncate(0);/* w ww.j a va 2s . c o m*/ LOG.info("Truncated block file " + f.getAbsolutePath()); s.close(); }
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();// w ww . j a v a 2 s.com outStream.close(); showNotification(saveFile); }
From source file:com.l2jfree.loginserver.L2LoginIdentifier.java
private synchronized void load() { if (isLoaded()) return;/*from www .ja va2s. c o m*/ File f = new File(System.getProperty("user.home", null), FILENAME); ByteBuffer bb = ByteBuffer.allocateDirect(8); if (!f.exists() || f.length() != 8) { _uid = getRandomUID(); _loaded = true; _log.info("A new UID has been generated for this login server."); FileOutputStream fos = null; try { f.createNewFile(); fos = new FileOutputStream(f); FileChannel fc = fos.getChannel(); bb.putLong(getUID()); bb.flip(); fc.write(bb); fos.flush(); } catch (IOException e) { _log.warn("Could not store login server's UID!", e); } finally { IOUtils.closeQuietly(fos); f.setReadOnly(); } } else { FileInputStream fis = null; try { fis = new FileInputStream(f); FileChannel fc = fis.getChannel(); fc.read(bb); } catch (IOException e) { _log.warn("Could not read stored login server's UID!", e); } finally { IOUtils.closeQuietly(fis); } if (bb.position() > 0) { bb.flip(); _uid = bb.getLong(); } else _uid = getRandomUID(); _loaded = true; } }